FileInfo Class and File Class

来源:互联网 发布:注册一个淘宝店 编辑:程序博客网 时间:2024/05/19 12:13

    The File object is a class that provides high-level functions to make copying, moving, deleting, and opening files easier. In addition, it provides some methods to aid in the creation of FileStreams. To make single calls easier, all the methods provided in the File class are static. The following Example demonstrates some of the features available in the File class and shows how to create a file using the File class.

using System;
using System.IO;

namespace SAMS.VisualCSharpUnleashed.Chapter7
{
  class FileExample
  {
    [STAThread]
    static void Main(string[] args)
    {
      // Create a new file
      string filePath = @"test.txt";

      //  Delete the file if it already exists 
      if(File.Exists(filePath))
        File.Delete(filePath);

      // Create the file
      File.Create(filePath);

      System.Console.WriteLine("The file was created.");
      System.Console.ReadLine();
    }
  }
}

    The FileInfo object is another class that provides high-level functions to make copying, moving, deleting, and opening files easier. In addition, it provides some methods to aid in the creation of streams. Unlike the File class, the FileInfo class is made up entirely of instance methods. The following Example  demonstrates how to use the FileInfo class to list information about a particular file.

using System;
using System.IO;

namespace SAMS.VisualCSharpUnleashed.Chapter7
{
    class Class1
    {
     [STAThread]
     static void Main(string[] args)
     {
           // Create a new file
          string filePath = @"c:/test.txt";

            FileInfo fi = new FileInfo(filePath);

            //  Print out the information if the file exists
            if(fi.Exists)
           {
               System.Console.WriteLine(
                  "The file: {0} was last accessed on {1} " +
                  " and contains {2} bytes of data.", filePath,
                  fi.LastAccessTime, fi.Length);
           }
          else
               System.Console.WriteLine("The file: {0} does not exist.", filePath);

          System.Console.ReadLine();
       }
    }
}

    Security checks are made on each call of the static methods in the File class. Because the FileInfo class is an instance class, the security checks need to be performed only once. A general rule of thumb to use when deciding which class to use is this: If you are performing a single operation on a file, the File class might be the right choice. If, however, you are performing multiple operations on a file, the FileInfo class is probably the most efficient choice.