Share via


File 类

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

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

语法

声明
<ComVisibleAttribute(True)> _
Public NotInheritable Class File
用法
可对静态类的成员直接进行访问,无需类的实例。
[ComVisibleAttribute(true)] 
public static class File
[ComVisibleAttribute(true)] 
public ref class File abstract sealed
/** @attribute ComVisibleAttribute(true) */ 
public final class File
ComVisibleAttribute(true) 
public final class File

备注

File 类用于典型的操作,如复制、移动、重命名、创建、打开、删除和追加到文件。也可将 File 类用于获取和设置文件属性或有关文件创建、访问及写入操作的 DateTime 信息。

许多 File 方法在您创建或打开文件时返回其他 I/O 类型。可以使用这些其他类型进一步处理文件。有关更多信息,请参见特定的 File 成员,如 OpenTextCreateTextCreate

由于所有的 File 方法都是静态的,所以如果只想执行一个操作,那么使用 File 方法的效率比使用相应的 FileInfo 实例方法可能更高。所有的 File 方法都要求当前所操作的文件的路径。

File 类的静态方法对所有方法都执行安全检查。如果打算多次重用某个对象,可考虑改用 FileInfo 的相应实例方法,因为并不总是需要安全检查。

默认情况下,将向所有用户授予对新文件的完全读/写访问权限。

下表描述了用于自定义各种 File 方法的行为的枚举。

枚举

说明

FileAccess

指定对文件的读取和写入访问。

FileShare

为已在使用中的文件指定允许的访问级别。

FileMode

指定是保留还是改写现有文件的内容,并指定创建现有文件的请求是否会导致异常。

提示

在接受路径作为输入字符串的成员中,路径必须是格式良好的,否则将引发异常。例如,如果路径是完全限定的但以空格开头,则路径在类的方法中不会被修剪。因此,路径的格式不正确,并将引发异常。同样,路径或路径的组合不能被完全限定两次。例如,“c:\temp c:\windows”在大多数情况下也将引发异常。在使用接受路径字符串的方法时,请确保路径是格式良好的。

在接受路径的成员中,路径可以是指文件或仅是目录。指定路径也可以是相对路径或者服务器和共享名称的统一命名约定 (UNC) 路径。例如,以下都是可接受的路径:

  • C# 中的“c:\\MyDir\\MyFile.txt”或 Visual Basic 中的“c:\MyDir\MyFile.txt”。

  • C# 中的“c:\\MyDir”或 Visual Basic 中的“c:\MyDir”。

  • C# 中的“MyDir\\MySubdir”或 Visual Basic 中的“MyDir\MySubDir”。

  • C# 中的“\\\\MyServer\\MyShare”或 Visual Basic 中的“\\MyServer\MyShare”。

有关此类的用法示例,请参见“示例”部分。下表列出了其他典型或相关的 I/O 任务的示例。

若要执行此操作...

请参见本主题中的示例...

创建文本文件。

如何:向文件写入文本

写入文本文件。

如何:向文件写入文本

读取文本文件。

如何:从文件读取文本

向文件中追加文本。

如何:打开并追加到日志文件

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

示例

下面的示例演示了 File 类的一些主要成员。

Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        If File.Exists(path) = False Then
            ' Create a file to write to.
            Dim sw As StreamWriter = File.CreateText(path)
            sw.WriteLine("Hello")
            sw.WriteLine("And")
            sw.WriteLine("Welcome")
            sw.Flush()
            sw.Close()
        End If

        Try
            ' Open the file to read from.
            Dim sr As StreamReader = File.OpenText(path)
            Do While sr.Peek() >= 0
                Console.WriteLine(sr.ReadLine())
            Loop
            sr.Close()
            Dim path2 As String = 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 e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path)) 
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }   
        }

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }

        try 
        {
            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());
        }
    }
}
using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   if (  !File::Exists( path ) )
   {
      
      // Create a file to write to.
      StreamWriter^ sw = File::CreateText( path );
      try
      {
         sw->WriteLine( "Hello" );
         sw->WriteLine( "And" );
         sw->WriteLine( "Welcome" );
      }
      finally
      {
         if ( sw )
                  delete (IDisposable^)(sw);
      }
   }

   // Open the file to read from.
   StreamReader^ sr = File::OpenText( path );
   try
   {
      String^ s = "";
      while ( s = sr->ReadLine() )
      {
         Console::WriteLine( s );
      }
   }
   finally
   {
      if ( sr )
            delete (IDisposable^)(sr);
   }

   try
   {
      String^ path2 = String::Concat( 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 );
   }
}
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        String path = "c:\\temp\\MyTest.txt";

        if (!(File.Exists(path))) {
            // Create a file to write to.
            StreamWriter sw = File.CreateText(path);

            try {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
            finally {
                sw.Dispose();
            }
        }

        // Open the file to read from.
        StreamReader sr = File.OpenText(path);

        try {
            String s = "";

            while ((s = sr.ReadLine()) != null) {
                Console.WriteLine(s);
            }
        }
        finally {
            sr.Dispose();
        }
        try {
            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 (System.Exception e) {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    } //main
} //Test

继承层次结构

System.Object
  System.IO.File

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

File 成员
System.IO 命名空间

其他资源

文件和流 I/O
如何:从文件读取文本
如何:向文件写入文本
基本的文件 I/O
如何:对新建的数据文件进行读取和写入