zoukankan      html  css  js  c++  java
  • C# 文件操作

    在.NET Framework中进行的所有的输入和输出工作都要用到流(stream),流是序列化设备(serial device)的抽象表示。

    System.IO包含了用于在文件中读写数据的类。

    File 类 静态实用类 提供静态方法 用于移动 复制和删除文件

    Directory 类静态实用类 提供静态方法 用于移动 复制和删除文件

    Path 类 用于处理路径名称

    FileInfo 类 表示磁盘上的物理文件,该类包含处理文件的方法。要完成对文件的读写工作,必须创建Stream对象。

    DirectoryInfo 类 表示磁盘上的文件,包含处理目录的方法。

    FileStreamInfo 用作FileInfo和DirectoryInfo的基类,可以使用多态性同时处理文件和目录。

    FileStream类 表示可读可写,或者均可的文件,此文件可以同步或一部的读写。

    SreamReader 从流中读取字符数据,可使用FileStream将其创建为基类。

    StreamWriter 向流中写入数据,使用FileStream将其创建为基类。

    FileSystemWatcher 用于监控文件和目录,提供了这些文件和目录发生变化时应用程序可以捕获的事件。

     

    System.IO.Compression 它允许使用GZIP压缩或Default压缩模式读写压缩文件。

    System.Runtime.Serialization.Formatters.Binary命名空间中的BinaryFormatter类允许把对象序列化为二进制数据流,并可以反序列化这些数据。

     

    FileStream aFile = new FileStream(filename,FileMode.Member,FileAccess.Member);

    FileStream aFile = File.OpenRead(“Data.txt”);

    FileInfo aFileInfo = new FileInfo(“Data.txt”);

    FileStream aFile = aFileInfo.OpenRead();

     

    DirectoryInfo dir = new DirectoryInfo(Path);

    FileSystemInfo[]fsi = dir.GetFileSystemInfos);//获取所有子目录及文件

     

    文件位置

    Seek()方法。

    AFile.Seek(8,SeekOrigin.Begin);//将文件指针移动到文件的第八个字节。

    FileStream myReadStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read);
                myReadStream.Seek(6, SeekOrigin.Begin);
                myReadStream.Read(byData, 0, 128);

    StreamReader

    实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。

    StreamReader 旨在以一种特定的编码输入字符,而 Stream 类用于字节的输入和输出。使用 StreamReader 读取标准文本文件的各行信息。

    除非另外指定,StreamReader 的默认编码为 UTF-8,而不是当前系统的 ANSI 代码页。UTF-8 可以正确处理 Unicode 字符并在操作系统的本地化版本上提供一致的结果。

    View Code
    try 
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader("TestFile.txt")) 
                {
                    String line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null) 
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception e) 
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
    View Code
    string path = @"c:\temp\MyTest.txt";
            try 
            {
                if (File.Exists(path)) 
                {
                    File.Delete(path);
                }
    
                using (StreamWriter sw = new StreamWriter(path)) 
                {
                    sw.WriteLine("This");
                    sw.WriteLine("is some text");
                    sw.WriteLine("to test");
                    sw.WriteLine("Reading");
                }
    
                using (StreamReader sr = new StreamReader(path)) 
                {
                    while (sr.Peek() >= 0) 
                    {
                        Console.WriteLine(sr.ReadLine());
                    }
                }
            } 
            catch (Exception e) 
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }

    读取数据最简单的方法是Read()方法。

    此方法将流的下一个字符作为正整数值返回,如果达到流的结尾处,返回-1.使用Convert实用类把这个值转化为字符。

    StreamReader  sr = new  StreamReader();

    Int nChar;

    nChar=sr.Read();

    While(nChar!=-1)

    {

    Console.Write(Convert.ToChar(nChar));

    nChar = sr.Read();

    }

    Sr.Close();

    StreamWriter 类

    实现一个 TextWriter,使其以一种特定的编码向流中写入字符。

    FileStream fs = new FileStream(fileName,  FileMode.CreateNew, FileAccess.Write, FileShare.None);      

               StreamWriter swFromFile = new StreamWriter(logFile);

                swFromFile.Write(textToAdd);

                swFromFile.Flush();

                swFromFile.Close();

    文件属性

    FileInfo fileInfo = new FileInfo(path);

    //去掉隐藏属性

    fileInfo.Attributes &= ~FileAttributes.Hidden;

    //去掉只读属性

    fileInfo.Attributes &= ~FileAttributes.ReadOnly;

    添加隐藏属性

    fileInfo.Attributes |= FileAttributes.Hidden;

    GetAttibutes()和SetAttributes()方法可以获取或设定文件属性。

    查找指定目录下的所有子目录和文件
     public void FindFile(string dir)
            {
                string[] Alldir = Directory.GetDirectories(dir);
                try
                {
                    foreach (string Strdir in Alldir)
                    {
                        FindFile(Strdir + "\\");
                        listBox1.Items.Add(Strdir + "\\");//添加目录名
                    }
                    foreach (string Strfile in Directory.GetFiles(dir))
                    {
                        listBox1.Items.Add(Strfile);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string path = "";
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    path = folderBrowserDialog1.SelectedPath;
                }
                if (path.Length > 1)
                {
                    if (path[path.Length - 1] != '\\')
                    {
                        path += "\\";
                    }
                }
                FindFile(path);
                //DirectoryInfo dir = new DirectoryInfo(path);
                //FileSystemInfo[] fsi = dir.GetFileSystemInfos();
                //foreach (FileSystemInfo f in fsi)
                //{
                //    listBox1.Items.Add(f.FullName);
                //}
            }
    读写压缩文件
     public static void SaveCompressionFile(string fileName, string data)
            {
                FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
                GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Compress);
                StreamWriter writer = new StreamWriter(compressionStream);
                writer.Write(data);
                writer.Close();
            }
    
            public static string LoadCompressionFile(string fileName)
            {
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Decompress);
                StreamReader reader = new StreamReader(compressionStream);
                string data = reader.ReadToEnd();
                return data;
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string path = "";
                openFileDialog1.InitialDirectory = "c:\\";
                openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                openFileDialog1.FilterIndex = 2;
                openFileDialog1.RestoreDirectory = true;
    
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {    
                        path = openFileDialog1.FileName;
                        //return new FileStream(path, System.IO.FileMode.Open,System.IO.FileAccess.ReadWrite);
                }
                try
                {
                    label1.Text = textBox1.Text.Length.ToString();
                    SaveCompressionFile(path, textBox1.Text.Trim());
                    FileInfo fileInfo = new FileInfo(path);
                    label2.Text = fileInfo.Length.ToString();
                    textBox2.Text = LoadCompressionFile(path);
                }
                catch(IOException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
    计算机上的驱动器
    class Program
        {
            static void Main(string[] args)
            {
                DriveInfo[] Drives;
                ArrayList hardDisk = new ArrayList(); ;
                Drives = DriveInfo.GetDrives();
                int drvCount = Drives.Length;
                Console.WriteLine("本地计算机上共有逻辑驱动器 " + drvCount + " 个,分别是:");
                foreach (DriveInfo item in Drives)
                {
                    Console.Write(item + "\t");
                    if (item.DriveType == DriveType.Fixed)
                    {
                        hardDisk.Add(item.ToString());
                    }
                }
                Console.WriteLine("\n本地计算机上共有本地驱动器 " + hardDisk.Count + " 个,分别是:");
                foreach (var Disk in hardDisk)
                {
                    Console.Write(Disk + "\t");
                }
                string drvName = @"E:\";
                DriveInfo drvInfo = new DriveInfo(drvName);
                Console.WriteLine("驱动器E的信息如下:");
                Console.WriteLine("名 称: " + drvInfo.Name);
                Console.WriteLine("卷 标: " + drvInfo.VolumeLabel);
                Console.WriteLine("驱动器类型: " + drvInfo.DriveType);
                Console.WriteLine("文件系统类型: " + drvInfo.DriveFormat);
                Console.WriteLine("总共空间大小:" + drvInfo.TotalSize);
                Console.WriteLine("剩余空间大小:" + drvInfo.TotalFreeSpace);
                Console.WriteLine("根目录:" + drvInfo .RootDirectory );
    
                //string path = @"D:\My Documents";
                //string[] AllFile = Directory.GetFiles(path);
                //ArrayList picFile = new ArrayList();
    
                //for (int i = 0; i < AllFile.Length; i++)
                //{
                //    FileInfo fi = new FileInfo(AllFile[i]);
                //    if (fi.Extension == ".jpg" || fi.Extension == ".bmp")
                //        picFile.Add(AllFile[i]);
                //}
                //foreach (string file in picFile)
                //{
                //    Console.WriteLine(file);
                //}
                //Console.WriteLine("共找到符合条件的:{0}个文件", picFile.Count.ToString());
                //string path = @"C:\aaa\bbb\ccc\dddd";
                //if (!Directory.Exists(path))
                //{
                //    Directory.CreateDirectory(path);
                //} 
                ////Directory类的Exists()方法用来判断目录是否存在,存在则返回true;  
                ////Directory类的CreateDirectory()方法用来创建目录  
    
                //得到所有文件
                //string[] AllFile = Directory.GetFiles(@"d:\Test");
                //foreach (string file in AllFile)
                //{
                //    File.Delete(file);
                //}
    
    
                //string filepath = @"D:\WorkList.txt";
                ////string filepath = @"F:\VStest\file.txt";
                //FileInfo myfile = new FileInfo(filepath);
                //FileStream fs = myfile.Create();
                //fs.Close();
                //myfile.Refresh();
                //myfile.Delete();
    
    
                Console.ReadKey();
            }
        }

    注:本文整理自网络!!!

  • 相关阅读:
    WPF中用户控件对比自定义控件(UserControl VS CustomControl) upcode
    WinCE7开发过程 upcode
    App/Shell启动过程 upcode
    WinCE启动过程 upcode
    ASP.NET 4.0验证请求 A potentially dangerous Request.Form value was detected from the client
    HTML5 开发工具推荐
    用.NET部署卸载window服务
    C#去除HTML标签方法
    正在中止线程 的问题解决
    【转载】纯CSS画的基本图形(矩形、圆形、三角形、多边形、爱心、八卦等)
  • 原文地址:https://www.cnblogs.com/YuanSong/p/2618022.html
Copyright © 2011-2022 走看看