kshen转浅析c#中的文件操作

来源:互联网 发布:淘宝上哪家零食店好 编辑:程序博客网 时间:2024/04/29 06:37
 

微软的.Net框架为我们提供了基于流的I/O操作方式,这样就大大简化了开发者的工作。因为我们可以对一系列的通用对象进行操作,而不必关心该I/O操作是和本机的文件有关还是和网络中的数据有关。.Net框架主要为我们提供了一个System.IO命名空间,该命名空间基本包含了所有和I/O操作相关的类。

本文将向大家介绍一些基本的文件操作方法,包括对文件系统中的目录和文件的操作,还有就是文件的读写操作等。通过运用System.IO.DirectoryInfo类和System.IO.FileInfo类我们可以轻易的完成与目录和文件相关的操作,而通过运用System.IO.StreamReader类和System.IO.StreamWriter类我们可以方便的完成与文件的读写相关的操作。

 

命名空间概览

下面的表格显示了System.IO命名空间中最重要的一些类,通过运用这些类我们就能完成基本的文件操作。

 

表1

 

类名 功能和用途 BinaryReader、BinaryWriter 读写二进制数据 Directory、File、DirectoryInfo以及FileInfo 创建、删除并移动目录和文件,通过属性获取特定目录和文件的相关信息 FileStream 以随机方式访问文件 MemoryStream 访问存储在内存中的数据 StreamReader 、StreamWriter 读写文本数据信息 StringReader、StringWriter 运用字符串缓冲读写文本数据信息

 

运用DirectoryInfo类和FileInfo类

DirectoryInfo类和FileInfo类的基类都是FileSystemInfo类,这个类是一个抽象类,也就是说你不可以实例化该类,只能通过继承产生其子类并实例化其子类。然而你却可以运用由该类定义的各种属性,下面的表格显示了该类已经定义了的各种属性。

 

表2

 

属性 功能和用途 Attributes 返回和文件相关的属性值,运用了FileAttributes枚举类型值 CreationTime 返回文件的创建时间 Exists 检查文件是否存在于给定的目录中 Extension 返回文件的扩展名 LastAccessTime 返回文件的上次访问时间 FullName 返回文件的绝对路径 LastWriteTime 返回文件的上次写操作时间 Name 返回给定文件的文件名 Delete() 删除一个文件的方法,请务必谨慎地运用该方法

DirectoryInfo类提供了创建、删除和移动目录等方法,要运用表2中的各种属性,我们首先得创建一个DirectoryInfo类的对象,然后就可以访问其各种属性了。

DirectoryInfo dir1 = new DirectoryInfo(@"F:/Test");Console.WriteLine("Full Name is : {0}", dir1.FullName);Console.WriteLine("Attributes are : {0}", dir1.Attributes.ToString());

同时,我们还可以运用FileAttributes枚举类型值来获取和文件相关的各种属性,下面的表格就显示了该枚举类型中的各种值。

 

表3

 

值 功能和用途 Archive 返回文件的存档状态 Compressed 返回文件是否被压缩 Directory 返回文件是否是一个目录 Encrypted 返回文件是否被加密 Hidden 返回文件是否是隐藏的 Offline 表明文件数据是不可得的 ReadOnly 表明文件是只读的 System 表明文件是一个系统文件

 

目录下的文件操作

运用DirectoryInfo类的对象我们可以轻松的实现对目录以及和目录中的文件相关的操作,假如你要获得某个目录F:/Pictures下的所有BMP文件,那么通过下面的代码就可以实现该功能。

DirectoryInfo dir = new DirectoryInfo(@"F:/ Pictures");FileInfo[] bmpfiles = dir.GetFiles("*.bmp);Console.WriteLine("Total number of bmp files", bmpfiles.Length);Foreach( FileInfo f in bmpfiles){  Console.WriteLine("Name is : {0}", f.Name);  Console.WriteLine("Length of the file is : {0}", f.Length);  Console.WriteLine("Creation time is : {0}", f.CreationTime);  Console.WriteLine("Attributes of the file are : {0}",                    f.Attributes.ToString());}

上面的代码中我们首先创建了一个DirectoryInfo对象,然后通过调用该对象的GetFiles方法获取目录F:/Pictures下的所有以bmp为扩展名的文件,该方法返回的值是一个FileInfo类型的数组,每个元素则代表一个文件。最后,程序还列举了每个BMP文件的相关属性。

 

创建子目录

运用DirectoryInfo类创建子目录是非常容易的,你只要调用其中CreateSubdirectory()方法即可,演示代码如下。

DirectoryInfo dir = new DirectoryInfo(@"F:/ Pictures");try{  dir.CreateSubdirectory("Sub");  dir.CreateSubdirectory(@"Sub/MySub");}catch(IOException e) {  Console.WriteLine(e.Message);}

 

运用FileInfo类创建、删除文件

通过FileInfo类,我们可以方便地创建出文件,并可以访问文件的属性同时还可以对文件进行打开文件、关闭文件、读写文件等基本的操作。下面的代码显示了如何创建一个文本文件并且去访问其创建时间、文件的绝对路径以及文件属性等文件信息,最后程序还给出了删除文件的方法。

FileInfo fi = new FileInfo(@"F:/Myprogram.txt");FileStream fs = fi.Create();Console.WriteLine("Creation Time: {0}",fi.CreationTime);Console.WriteLine("Full Name: {0}",fi.FullName);Console.WriteLine("FileAttributes: {0}",fi.Attributes.ToString());Console.WriteLine("Press any key to delete the file");Console.Read();fstr.Close();fi.Delete();

 

理解FileInfo类的Open()方法

我们在对文件进行读写操作之前必须打开文件,FileInfo类为我们提供了一个Open()方法,该方法包含了两个枚举类型值的参数,一个为FileMode枚举类型值,另一个为FileAccess枚举类型值。通过设定这两个参数值,我们可以对文件的访问模式和操作权限进行控制。下面的两个表格分别显示了FileMode枚举类型的值和FileAccess枚举类型的值。

 

表4

 

值 功能和用途 Append 打开文件并添加数据,运用该方法时FileAccess枚举类型值应为Write。 Create 创建一个新文件,有可能会覆盖已经存在的文件。 CreateNew 创建一个新文件,如果该文件已经存在,则抛出IOException异常。 Open 打开一个已经存在的文件。 OpenOrCreate 打开文件,如果该文件不存在,则创建之。 Truncate 截短一个已经存在的文件。

 

表5

 

值 功能和用途 Read 可以从一个文件中读取数据。 ReadWrite 可以从一个文件中读取数据,同时还可以向文件中写入数据。 Write 可以向文件中写入数据。

下面的代码显示了Open()方法的具体运用方法。

FileInfo f = new FileInfo("F:/MyFile.txt");FileStream s = f.Open(FileMode.OpenorWrite, FileAccess.Read);

 

运用StreamReader类和StreamWriter类实现文件的读写操作

对文件的读写操作应该是最重要的文件操作,System.IO命名空间为我们提供了诸多文件读写操作类,在这里我要向大家介绍最常用也是最基本的StreamReader类和StreamWriter类。从这两个类的名称我们不难发现它们都是基于流的读写操作类。

我们可以通过File类的OpenText()方法来获取一个StreamReader对象,通过该对象我们可以实现对文本文件的读操作,方法如下:

Console.WriteLine("Reading the contents from the file");StreamReader s = File.OpenText("MyText.txt");string read = null;while ((read = s.ReadLine()) != null){  Console.WriteLine(read);}s.Close();

而通过调用FileInfo类的CreateText()方法我们可以获取一个StreamWriter对象,调用StreamWriter类的WriteLine()我们就可以向文本文件中写入数据了,方法如下:

FileInfo f = new FileInfo("MyText.txt")StreamWriter w = f.CreateText();w.WriteLine("This is from");w.WriteLine("Chapter 1");w.WriteLine("Of C# Module");w.Write(w.NewLine);w.WriteLine("Thanks for your time");w.Close();

 

总结

以上我简要地向大家介绍了C#文件操作的基本知识和方法,通过本文大家不难发现.Net框架下I/O操作的方便性。读者在学习了本文后,如果要进行一些基本的文件操作,那么对于System.IO命名空间中的诸如DirectoryInfo类、FileInfo类、FileStream类、StreamReader类以及StreamWriter类等类一定得有基本了解并在实际应用中灵活使用之。如果要对文件操作有更进一步的控制,那么不妨去研究一下System.IO命名空间中的更为具体和细节的一些类。最后,希望本文对大家能有所帮助。

另1:

--------------------------------------------------------------------------------
文件操作

若要执行此操作... 请参阅本主题中的示例...
创建文本文件 向文件写入文本 
写入文本文件 向文件写入文本 
读取文本文件 从文件读取文本 
向文件中追加文本 File.AppendText FileInfo.AppendText 
重命名或移动文件 File.Move FileInfo.MoveTo 
删除文件 File.Delete FileInfo.Delete 
复制文件 File.Copy FileInfo.CopyTo 
获取文件大小 FileInfo.Length 
获取文件属性 File.GetAttributes 
设置文件属性 File.SetAttributes 
确定文件是否存在 File.Exists 
读取二进制文件 对刚创建的数据文件进行读取和写入 
写入二进制文件 对刚创建的数据文件进行读取和写入 
检索文件扩展名 Path.GetExtension 
检索文件的完全限定路径 Path.GetFullPath 
检索路径中的文件名和扩展名 Path.GetFileName 
更改文件扩展名 Path.ChangeExtension 

目录操作

System.IO 类

目录操作
string[] drives = Directory.GetLogicalDrives(); //本地驱动器的名,如:C:/等
string path = Directory.GetCurrentDirectory();  //获取应用程序的当前工作目录
Path.GetFileName(@"c:/dir/file.txt");           //获取子目录的名字,result的结果是file.txt
Directory.GetFiles(路径及文件名)                //获取指定目录中的文件名(文件列表)
DirectoryInfo di = new DirectoryInfo(@"f:/MyDir"); //构造函数创建目录
DirectoryInfo di=Directory.CreateDirectory(@"f:/bbs"); //创建对象并创建目录
if (di.Exists == false) //检查是否存在此目录
di.Create(); //创建目录
DirectoryInfo dis = di.CreateSubdirectory("SubDir"); //以相对路径创建子目录
dis.Delete(true); //删除刚创建的子目录
di.Delete(true); //删除创建目录

文件操作
Directory.Delete(@"f:/bbs2", true); //删除目录及其子目录和内容(如为假不能删除有内容的目录包括子目录)
Directory.GetDirectories 方法 //获取指定目录中子目录的名称
string[] dirs = Directory.GetDirectories(@"f:/", "b*");
Console.WriteLine("此目录中以b开头的子目录共{0}个!", dirs.Length);
foreach (string dir in dirs) { Console.WriteLine(dir); }
Directory.GetFileSystemEntries //获取指定目录中的目录及文件名
Directory.GetLogicalDrives //检索此计算机上格式为“<驱动器号>:/”的逻辑驱动器的名称,【语法同上】
Directory.GetParent //用于检索父目录的路径。
DirectoryInfo a = Directory.GetParent(path);
Console.WriteLine(a.FullName);Directory.Move //移动目录及其在内的所有文件
Directory.Move(@"f:/bbs/1", @"f:/bbs/2"); //将文件夹1内的文件剪到文件夹2内 文件夹2是刚创建的

 

Stream // 对字节的读写操作(包含对异步操作的支持) Reading Writing Seeking

BinaryReader和BinaryWriter // 从字符串或原始数据到各种流之间的读写操作

FileStream类通过Seek()方法进行对文件的随机访问,默认为同步

TextReader和TextWriter //用于gb2312字符的输入和输出

StringReader和StringWriter //在字符串中读写字符

StreamReader和StreamWriter //在流中读写字符

BufferedStream 为诸如网络流的其它流添加缓冲的一种流类型.

MemoryStream 无缓冲的流

NetworkStream 互联网络上的流



//编码转换
Encoding e1 = Encoding.Default;               //取得本页默认代码
Byte[] bytes = e1.GetBytes("中国人民解放军"); //转为二进制
string str = Encoding.GetEncoding("UTF-8").GetString(bytes); //转回UTF-8编码

 




//文本文件操作:创建/读取/拷贝/删除
using System;
using System.IO;
class Test
{
   string path = @"f:/t.txt";
   public static void Main()
   {       
      //创建并写入(将覆盖已有文件)
      if (!File.Exists(path))
      {         
         using (StreamWriter sw = File.CreateText(path))
         {
            sw.WriteLine("Hello");
         }
      }
      //读取文件
      using (StreamReader sr = File.OpenText(path))
      {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
           Console.WriteLine(s);
        }
     }
     //删除/拷贝
     try
     {
        File.Delete(path);
        File.Copy(path, @"f:/tt.txt");
     }
     catch (Exception e)
     {
        Console.WriteLine("The process failed: {0}", e.ToString());
     }
   }
}


//流文件操作
private const string name = "Test.data";
public static void Main(String[] args)
{
    //打开文件()  ,或通过File创建立如:fs = File.Create(path, 1024)
    FileStream fs = new FileStream(name, FileMode.CreateNew);
    //转换为字节 写入数据(可写入中文)
    Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
    //字节数组,字节偏移量,最多写入的字节数
    fs.Write(info, 0, info.Length);
    w.Close();
    fs.Close();
    //打开文件
    fs = new FileStream(name, FileMode.Open, FileAccess.Read);
    //读取
    BinaryReader r = new BinaryReader(fs);
    for (int i = 0; i < 11; i++)
    {
        Console.WriteLine(r.ReadInt32());
    }
    w.Close();
    fs.Close();
}

另2:

示例

Visual Basic
复制代码
Imports SystemImports System.IOClass Test    Public Shared Sub Main()        Try            ' Create an instance of StreamReader to read from a file.            Using sr As StreamReader = New StreamReader("TestFile.txt")                Dim line As String                ' Read and display the lines from the file until the end                 ' of the file is reached.                Do                    line = sr.ReadLine()                    Console.WriteLine(Line)                Loop Until line Is Nothing                sr.Close()            End Using        Catch E As Exception            ' Let the user know what went wrong.            Console.WriteLine("The file could not be read:")            Console.WriteLine(E.Message)        End Try    End SubEnd Class
C#
复制代码
using System;using System.IO;class Test {    public static void Main()     {        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);        }    }}
Visual Basic
复制代码
Option Explicit On Option Strict OnImports SystemImports System.IOPublic Class TextFromFile    Private Const FILE_NAME As String = "MyFile.txt"    Public Shared Sub Main()        If Not File.Exists(FILE_NAME) Then            Console.WriteLine("{0} does not exist.", FILE_NAME)            Return        End If        Using sr As StreamReader = File.OpenText(FILE_NAME)            Dim input As String            input = sr.ReadLine()            While Not input Is Nothing                Console.WriteLine(input)                input = sr.ReadLine()            End While            Console.WriteLine("The end of the stream has been reached.")            sr.Close()        End Using    End SubEnd Class
C#
复制代码
using System;using System.IO;public class TextFromFile {    private const string FILE_NAME = "MyFile.txt";    public static void Main(String[] args)     {        if (!File.Exists(FILE_NAME))         {            Console.WriteLine("{0} does not exist.", FILE_NAME);            return;        }        using (StreamReader sr = File.OpenText(FILE_NAME))        {            String input;            while ((input=sr.ReadLine())!=null)             {                Console.WriteLine(input);            }            Console.WriteLine ("The end of the stream has been reached.");            sr.Close();        }    }

可靠编程

此代码通过调用 File.OpenText 创建一个指向 MyFile.txt 的 StreamReader。StreamReader.ReadLine 将每一行都作为一个字符串返回。当不再有要读取的字符时,会有一条消息显示该情况,然后流关闭。