C#文件操作基本知识

来源:互联网 发布:威发半导体 知乎 编辑:程序博客网 时间:2024/05/05 21:48

 1、System.IO 命名空间包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。

2、我们常见的用到的类主要有:

 Directory 公开用于创建、移动和枚举通过目录和子目录的静态方法。无法继承此类。
 DirectoryInfo 公开用于创建、移动和枚举目录和子目录的实例方法。无法继承此类。

    File 提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建 FileStream 对象。

   FileInfo 提供创建、复制、删除、移动和打开文件的实例方法,并且帮助创建 FileStream 对象。无法继承此类。

  FileStream 公开以文件为主的 Stream,既支持同步读写操作,也支持异步读写操作。

  FileSystemInfo FileInfoDirectoryInfo 对象提供基类。

  Path 对包含文件或目录路径信息的 String 实例执行操作。这些操作是以跨平台的方式执行的。

  MemoryStream 创建其支持存储区为内存的流。

 

 Stream 提供字节序列的一般视图。
 StreamReader 实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。
 StreamWriter 实现一个 TextWriter,使其以一种特定的编码向流中写入字符。
 StringReader 实现从字符串进行读取的 TextReader
 StringWriter 实现一个用于将信息写入字符串的 TextWriter。该信息存储在基础 StringBuilder 中。
 TextReader 表示可读取连续字符系列的读取器。
 TextWriter

表示可以编写一个有序字符系列的编写器。该类为抽象类。

 

 

 3、其中常见的操作文本文件,通过使用 ReadAllLinesReadAllText 方法也可以实现此功能。

下面演示了读取文本文件:

  1. using System;
  2. using System.IO;
  3. class Test 
  4. {
  5.     public static void Main() 
  6.     {
  7.         try 
  8.         {
  9.             /// 创建StreamReader 的实例,使用using子句自动调用对象的销毁方法
  10.             using (StreamReader sr = new StreamReader("TestFile.txt")) 
  11.             {
  12.                 String line;
  13.                 //  读取文件内容并显示到控制台
  14.                 while ((line = sr.ReadLine()) != null
  15.                 {
  16.                     Console.WriteLine(line);
  17.                 }
  18.             }
  19.         }
  20.         catch (Exception e) 
  21.         {
  22.             // 输出异常消息
  23.             Console.WriteLine("The file could not be read:");
  24.             Console.WriteLine(e.Message);
  25.         }
  26.     }
  27. }

下面演示了写文本文件

  1. using System;
  2. using System.IO;
  3. class Test 
  4. {
  5.     public static void Main() 
  6.     {
  7.         // 创建StreamWriter实例,并且使用了using子句
  8.         using (StreamWriter sw = new StreamWriter("TestFile.txt")) 
  9.         {
  10.             // 写内容
  11.             sw.Write("This is the ");
  12.             sw.WriteLine("header for the file.");
  13.             sw.WriteLine("-------------------");
  14.             // 对象也可以写入文件
  15.             sw.Write("The date is: ");
  16.             sw.WriteLine(DateTime.Now);
  17.         }
  18.     }
  19. }

 

 

更多精彩,请查询MSDN.

原创粉丝点击