加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

file类详细使用方法

(2009-08-10 17:28:03)
标签:

name

read

sw

it

System.IO.File类和System.IO.FileInfo类主要提供有关文件的各种操作,在使用时需要引用System.IO命名空间。下面通过程序实例来介绍其主要属性和方法。
(1) 文件打开方法:File.Open ()
  该方法的声明如下:

     public static FileStream Open(string path,FileMode mode)
     参数:
     path    要打开的文件。

     mode    FileMode (枚举类型) 值,用于指定在文件不存在时是否创建该文件,并确定是保留还是改写现有文件的内容。
     返回值:
     以指定模式打开的指定路径上的 FileStream,具有读/写访问权限并且不共享。
     FileMode 枚举
     指定操作系统打开文件的方式。

     命名空间:System.IO
     程序集:mscorlib(在 mscorlib.dll 中)

     成员名称             说明
     Append               打开现有文件并查找到文件尾,或创建新文件。FileMode.Append 只能同   FileAccess.Write 一起使用。任何读 尝试都将失败并引发 ArgumentException。 
     Create               指定操作系统应创建新文件。如果文件已存在,它将被改写。这要求 FileIOPermissionAccess.Write。                                   System.IO.FileMode.Create 等效于这样的请求:如果文件不存在,则使用 CreateNew;否则使用 Truncate。 
     CreateNew            指定操作系统应创建新文件。此操作需要 FileIOPermissionAccess.Write。如果文件已存在,则将引发                                   IOException。 
     Open                 指定操作系统应打开现有文件。打开文件的能力取决于 FileAccess 所指定的值。如果该文件不存在,则引发                              System.IO.FileNotFoundException。 
     OpenOrCreate         指定操作系统应打开文件(如果文件存在);否则,应创建新文件。如果用 FileAccess.Read 打开文件,则需要                           FileIOPermissionAccess.Read。如果文件访问为 FileAccess.Write 或 FileAccess.ReadWrite,则需要                                  FileIOPermissionAccess.Write。如果文件访问为 FileAccess.Append,则需要                                                     FileIOPermissionAccess.Append。 
     Truncate             指定操作系统应打开现有文件。文件一旦打开,就将被截断为零字节大小。此操作需要                                                  FileIOPermissionAccess.Write。试图从使用 Truncate 打开的文件中进行读取将导致异常。
     FileMode 参数控制是否对文件执行改写、创建、打开等操作,或执行这些操作的组合。使用 Open 打开现有文件。若要追加到文件,请     使用 Append。若要截断文件或创建不存在的文件,请使用 Create。

     exp1:如何向文件写入文本

     下面的代码示例演示如何向文本文件中写入文本。

     第一个示例演示如何向现有文件中添加文本。第二个示例演示如何创建一个新文本文件并向其中写入一个字符串。 WriteAllText 方法可     提供类似的功能。
     using System;
     using System.IO;

     class Test
     {
      public static void Main()
      {
        // Create an instance of StreamWriter to write text to a file.
        // The using statement also closes the StreamWriter.
        using (StreamWriter sw = new StreamWriter("TestFile.txt"))
        {
            // Add some text to the file.
            sw.Write("This is the ");
            sw.WriteLine("header for the file.");
            sw.WriteLine("-------------------");
            // Arbitrary objects can also be written to the file.
            sw.Write("The date is: ");
            sw.WriteLine(DateTime.Now);
        }
      }
     }

     using System;
     using System.IO;
     public class TextToFile
     {
      private const string FILE_NAME = "MyFile.txt";
      public static void Main(String[] args)
      {
        if (File.Exists(FILE_NAME))
        {
            Console.WriteLine("{0} already exists.", FILE_NAME);
            return;
        }
        using (StreamWriter sw = File.CreateText(FILE_NAME))
        {
            sw.WriteLine ("This is my file.");
            sw.WriteLine ("I can write ints {0} or floats {1}, and so on.",
                1, 4.2);
            sw.Close();
        }
       }
      }
     exp2:如何从文件读取文本

     下面的代码示例演示如何从文本文件中读取文本。第二个示例在检测到文件结尾时向您发出通知。通过使用 ReadAllLines 或           ReadAllText 方法也可以实现此功能。
    
     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);
        }
      }
     }
     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();
        }
      }
    
      exp3::如何对新建的数据文件进行读取和写入二进制文件

      BinaryWriter 和 BinaryReader 类用于读取和写入数据,而不是字符串。下面的代码示例演示如何向新的空文件流 (Test.data) 写入      数据及从中读取数据。在当前目录中创建了数据文件之后,也就同时创建了相关的 BinaryWriter 和 BinaryReader,BinaryWriter 用      于向 Test.data 写入整数 0 到 10,Test.data 将文件指针置于文件尾。在将文件指针设置回初始位置后,BinaryReader 读出指定的      内容。

      using System;
      using System.IO;
      class MyStream
      {
        private const string FILE_NAME = "Test.data";
        public static void Main(String[] args)
        {
        // Create the new, empty data file.
        if (File.Exists(FILE_NAME))
        {
            Console.WriteLine("{0} already exists!", FILE_NAME);
            return;
        }
        FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);
        // Create the writer for data.
        BinaryWriter w = new BinaryWriter(fs);
        // Write data to Test.data.
        for (int i = 0; i < 11; i++)
        {
            w.Write( (int) i);
        }
        w.Close();
        fs.Close();
        // Create the reader for data.
        fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
        BinaryReader r = new BinaryReader(fs);
        // Read data from Test.data.
        for (int i = 0; i < 11; i++)
        {
            Console.WriteLine(r.ReadInt32());
        }
        r.Close();
        fs.Close();
       }
      }
      如果 Test.data 已存在于当前目录中,则引发一个 IOException。始终使用 FileMode.Create 创建新文件,而不引发 IOException。
     
      exp4:如何打开并追加到日志文件
     
      StreamWriter 和 StreamReader 向流写入字符并从流读取字符。下面的代码示例打开 log.txt 文件(如果文件不存在则创建文件)以      进行输入,并将信息附加到文件尾。然后将文件的内容写入标准输出以便显示。除此示例演示的做法外,还可以将信息存储为单个字符      串或字符串数组, WriteAllText 或 WriteAllLines 方法可以用于实现相同的功能。

      using System;
      using System.IO;
      class DirAppend
      {
       public static void Main(String[] args)
       {
        using (StreamWriter w = File.AppendText("log.txt"))
        {
            Log ("Test1", w);
            Log ("Test2", w);
            // Close the writer and underlying file.
            w.Close();
        }
        // Open and read the file.
        using (StreamReader r = File.OpenText("log.txt"))
        {
            DumpLog (r);
        }
       }
       public static void Log (String logMessage, TextWriter w)
       {
        w.Write("\r\nLog Entry : ");
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
            DateTime.Now.ToLongDateString());
        w.WriteLine("  :");
        w.WriteLine("  :{0}", logMessage);
        w.WriteLine ("-------------------------------");
        // Update the underlying file.
        w.Flush();
       }
       public static void DumpLog (StreamReader r)
       {
        // While not at the end of the file, read and write lines.
        String line;
        while ((line=r.ReadLine())!=null)
        {
            Console.WriteLine(line);
        }
        r.Close();
       }
      }

    下面的代码打开存放在c:\tempuploads目录下名称为newFile.txt文件,并在该文件中写入hello。

private void OpenFile()
{
  FileStream.TextFile=File.Open(@"c:\tempuploads\newFile.txt",FileMode.Append);
  byte [] Info = {(byte)'h',(byte)'e',(byte)'l',(byte)'l',(byte)'o'};
  TextFile.Write(Info,0,Info.Length);
  TextFile.Close();
}

    (2) 文件创建方法:File.Create()
     File.Create 方法 (String path)  在指定路径中创建文件。
     返回值:一个 FileStream,它提供对 path 中指定的文件的读/写访问。
     异常:
     异常类型                        条件
     UnauthorizedAccessException     调用方没有所要求的权限。
                                     - 或 -
                                     path 指定了一个只读文件。
 
     ArgumentException               path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符
 
     ArgumentNullException           path 为 空引用(在 Visual Basic 中为 Nothing)。
 
     PathTooLongException            指定的路径、文件名或者两者都超出了系统定义的最大长度。例如,在基于 Windows 的平台上,路                                     径必须小于 248 个字符,文件名必须小于 260 个字符。
 
     DirectoryNotFoundException      指定的路径无效(例如,它位于未映射的驱动器上)。
 
     IOException                     创建文件时发生 I/O 错误。
 
     NotSupportedException           path 的格式无效。
 
 

  该方法的声明如下:
      public static FileStream Create(string path;)
由此方法创建的 FileStream 对象的 FileShare 值默认为 None;直到关闭原始文件句柄后,其他进程或代码才能访问这个创建的文件。

此方法等效于使用默认缓冲区大小的 Create(String,Int32) 方法重载。

允许 path 参数指定相对或绝对路径信息。相对路径信息被解释为相对于当前工作目录。若要获取当前工作目录,请参见 GetCurrentDirectory。

如果指定的文件不存在,则创建该文件;如果存在并且不是只读的,则将改写其内容。

默认情况下,将向所有用户授予对新文件的完全读/写访问权限。文件是用读/写访问权限打开的,必须关闭后才能由其他应用程序打开。


  下面的代码演示如何在c:\tempuploads下创建名为newFile.txt的文件。
  由于File.Create方法默认向所有用户授予对新文件的完全读/写访问权限,所以文件是用读/写访问权限打开的,必须关闭后才能由其他应用程序打开。为此,所以需要使用FileStream类的Close方法将所创建的文件关闭。
下面的示例在指定路径中创建一个文件,将一些信息写入该文件,再从文件中读取。
EXP1:
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        try
        {

            // Delete the file if it exists.
            if (File.Exists(path))
            {
                // Note that no lock is put on the
                // file and the possibliity exists
                // that another process could do
                // something with it between
                // the calls to Exists and Delete.
                File.Delete(path);
            }

            // Create the file.
            using (FileStream fs = File.Create(path))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }

            // Open the stream and read it back.
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }

        catch (Exception Ex)
        {
            Console.WriteLine(Ex.ToString());
        }
    }
}

private void MakeFile()
{  
    FileStream NewText=File.Create(@"c:\tempuploads\newFile.txt");
   NewText.Close();
}
      (2).(1):File.Create 方法 (String, Int32)
           创建或改写指定的文件。

       参数
       path           文件名。
       bufferSize     用于读取和写入文件的已放入缓冲区的字节数。
       返回值
       一个具有指定缓冲大小的 FileStream,它提供对 path 中指定的文件的读/写访问。
      下面的示例创建一个具有指定缓冲区大小的文件。

using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        // Create the file.
        using (FileStream fs = File.Create(path, 1024))
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        // Open the stream and read it back.
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
      (3) 文件删除方法:File.Delete(string path)
     如果指定的文件不存在,则不引发异常。
   该方法声明如下:
      public static void Delete(string path);
     异常类型                         条件
     ArgumentException                path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。
 
     ArgumentNullException            path 为 空引用(在 Visual Basic 中为 Nothing)。
 
     DirectoryNotFoundException       指定的路径无效(例如,它位于未映射的驱动器上)。
 
     IOException                      指定的文件正在使用中。
    
     NotSupportedException            path 的格式无效。
 
     PathTooLongException             指定的路径、文件名或者两者都超出了系统定义的最大长度。例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。
 
     UnauthorizedAccessException      调用方没有所要求的权限。

                                      - 或 -

                                      path 是一个目录。

                                      - 或 -

                                      path 指定一个只读文件。
 

  下面的代码演示如何删除c:\tempuploads目录下的newFile.txt文件。

private void DeleteFile()
{
   File.Delete(@"c:\tempuploads\newFile.txt");
}

    EXP:
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        try
        {
            using (StreamWriter sw = File.CreateText(path)) {}
            string path2 = path + "temp";

            // Ensure that the target does not exist.
            File.Delete(path2);

            // Copy the file.
            File.Copy(path, path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);

            // Delete the newly created file.
            File.Delete(path2);
            Console.WriteLine("{0} was successfully deleted.", path2);
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

  (4) 文件复制方法:File.Copy
  该方法声明如下:
      public static void Copy(string sourceFileName,string destFileName,bool overwrite);
  下面的代码将c:\tempuploads\newFile.txt复制到c:\tempuploads\BackUp.txt。
  由于Cope方法的OverWrite参数设为true,所以如果BackUp.txt文件已存在的话,将会被复制过去的文件所覆盖。
    如果bool不指定,则不允许改写同名的文件。

private void CopyFile()
{
   File.Copy(@"c:\tempuploads\newFile.txt",@"c:\tempuploads\BackUp.txt",true);
}
  (5) 文件移动方法:File.Move
    将指定文件移到新位置,并提供指定新文件名的选项。

    该方法声明如下:
      public static void Move(string sourceFileName,string destFileName);
     参数
     sourceFileName      要移动的文件的名称。
     destFileName        文件的新路径。

     异常类型                         条件
     IOException                      目标文件已经存在。
     ArgumentNullException            sourceFileName 或 destFileName 为 空引用(在 Visual Basic 中为 Nothing)。
     ArgumentException                sourceFileName 或 destFileName 是零长度字符串、只包含空白或者包含在 InvalidPathChars 中定义的无效字符。
     UnauthorizedAccessException      调用方没有所要求的权限。
     FileNotFoundException            未找到 sourceFileName。
     PathTooLongException             指定的路径、文件名或者两者都超出了系统定义的最大长度。例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。
     DirectoryNotFoundException       sourceFileName 或 destFileName 中指定的路径无效(例如,它位于未映射的驱动器上)。
     NotSupportedException            sourceFileName 或 destFileName 的格式无效。
 

  下面的代码可以将c:\tempuploads下的BackUp.txt文件移动到c盘根目录下。
  注意:
  只能在同一个逻辑盘下进行文件转移。如果试图将c盘下的文件转移到d盘,将发生错误。
exp:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp2\MyTest.txt";
        try
        {
            if (!File.Exists(path))
            {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                using (FileStream fs = File.Create(path)) {}
            }

            // Ensure that the target does not exist.
            if (File.Exists(path2))   
            File.Delete(path2);

            // Move the file.
            File.Move(path, path2);
            Console.WriteLine("{0} was moved to {1}.", path, path2);

            // See if the original exists now.
            if (File.Exists(path))
            {
                Console.WriteLine("The original file still exists, which is unexpected.");
            }
            else
            {
                Console.WriteLine("The original file no longer exists, which is expected.");
                     

        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

EXP:

private void MoveFile()
{
   File.Move(@"c:\tempuploads\BackUp.txt",@"c:\BackUp.txt");
}

  

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有