FileInfo 类

定义

提供用于创建、复制、删除、移动和打开文件的属性和实例方法,并且帮助创建 FileStream 对象。Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. 此类不能被继承。This class cannot be inherited.

public ref class FileInfo sealed : System::IO::FileSystemInfo
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class FileInfo : System.IO.FileSystemInfo
type FileInfo = class
    inherit FileSystemInfo
Public NotInheritable Class FileInfo
Inherits FileSystemInfo
继承
属性

示例

下面的示例演示了FileInfo类的一些主要成员。The following example demonstrates some of the main members of the FileInfo class.

第一次检索属性时, FileInfoRefresh调用方法并缓存有关文件的信息。When the properties are first retrieved, FileInfo calls the Refresh method and caches information about the file. 在后续调用中, 必须调用Refresh以获取信息的最新副本。On subsequent calls, you must call Refresh to get the latest copy of the information.

using namespace System;
using namespace System::IO;

int main()
{
   String^ path = Path::GetTempFileName();
   FileInfo^ fi1 = gcnew FileInfo( path );
   //Create a file to write to.
   StreamWriter^ sw = fi1->CreateText();
   try
   {
     sw->WriteLine( "Hello" );
     sw->WriteLine( "And" );
     sw->WriteLine( "Welcome" );
   }
   finally
   {
     if ( sw )
        delete (IDisposable^)sw;
   }

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

   try
   {
      String^ path2 = Path::GetTempFileName();
      FileInfo^ fi2 = gcnew FileInfo( path2 );

      //Ensure that the target does not exist.
      fi2->Delete();

      //Copy the file.
      fi1->CopyTo( path2 );
      Console::WriteLine( "{0} was copied to {1}.", path, path2 );

      //Delete the newly created file.
      fi2->Delete();
      Console::WriteLine( "{0} was successfully deleted.", path2 );
   }
   catch ( Exception^ e )
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
using System;
using System.IO;

class Test 
{
    
    public static void Main() 
    {
        string path = Path.GetTempFileName();
        var fi1 = new FileInfo(path);

        // Create a file to write to.
        using (StreamWriter sw = fi1.CreateText()) 
        {
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome");
        }	

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

        try 
        {
            string path2 = Path.GetTempFileName();
            var fi2 = new FileInfo(path2);

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

            // Copy the file.
            fi1.CopyTo(path2);
            Console.WriteLine($"{path} was copied to {path2}.");

            // Delete the newly created file.
            fi2.Delete();
            Console.WriteLine($"{path2} was successfully deleted.");

        } 
        catch (Exception e) 
        {
            Console.WriteLine($"The process failed: {e.ToString()}");
        }
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        Dim path1 As String = Path.GetTempFileName()
        Dim path2 As String = Path.GetTempFileName()
        Dim fi As New FileInfo(path1)

        ' Create a file to write to.
        Using sw As StreamWriter = fi.CreateText()
            sw.WriteLine("Hello")
            sw.WriteLine("And")
            sw.WriteLine("Welcome")
        End Using

        Try
            ' Open the file to read from.
            Using sr As StreamReader = fi.OpenText()
                Do While sr.Peek() >= 0
                    Console.WriteLine(sr.ReadLine())
                Loop
            End Using

            Dim fi2 As New FileInfo(path2)

            ' Ensure that the target does not exist.
            fi2.Delete()

            ' Copy the file.
            fi.CopyTo(path2)
            Console.WriteLine($"{path1} was copied to {path2}.")

            ' Delete the newly created file.
            fi2.Delete()
            Console.WriteLine($"{path2} was successfully deleted.")

        Catch e As Exception
            Console.WriteLine($"The process failed: {e.ToString()}.")
        End Try
    End Sub
End Class

此示例生成与下面类似的输出。This example produces output similar to the following.

Hello  
And  
Welcome  
C:\Users\userName\AppData\Local\Temp\tmp70AB.tmp was copied to C:\Users\userName\AppData\Local\Temp\tmp70CB.tmp.  
C:\Users\userName\AppData\Local\Temp\tmp70CB.tmp was successfully deleted.  

注解

FileInfo使用类执行典型操作, 例如复制、移动、重命名、创建、打开、删除和追加到文件。Use the FileInfo class for typical operations such as copying, moving, renaming, creating, opening, deleting, and appending to files.

如果对同一文件执行多个操作, 则使用FileInfo实例方法而不是File类的相应静态方法会更有效, 因为并不总是需要安全检查。If you are performing multiple operations on the same file, it can be more efficient to use FileInfo instance methods instead of the corresponding static methods of the File class, because a security check will not always be necessary.

FileInfo许多方法在您创建或打开文件时返回其他 i/o 类型。Many of the FileInfo methods return other I/O types when you create or open files. 您可以使用这些其他类型进一步操作文件。You can use these other types to further manipulate a file. 有关详细信息, 请参阅FileInfo OpenOpenRead OpenText、、或Create等特定成员。 CreateTextFor more information, see specific FileInfo members such as Open, OpenRead, OpenText, CreateText, or Create.

默认情况下, 将向所有用户授予对新文件的完全读/写访问权限。By default, full read/write access to new files is granted to all users.

下表描述了用于自定义各种FileInfo方法的行为的枚举。The following table describes the enumerations that are used to customize the behavior of various FileInfo methods.

枚举Enumeration 说明Description
FileAccess 指定对文件的读取和写入访问权限。Specifies read and write access to a file.
FileShare 指定已在使用的文件所允许的访问级别。Specifies the level of access permitted for a file that is already in use.
FileMode 指定是保留还是覆盖现有文件的内容, 以及创建现有文件的请求是否会引发异常。Specifies whether the contents of an existing file are preserved or overwritten, and whether requests to create an existing file cause an exception.

备注

在接受路径作为输入字符串的成员中, 该路径必须格式正确, 否则会引发异常。In members that accept a path as an input string, that path must be well-formed or an exception is raised. 例如, 如果路径是完全限定的, 但以空格开头, 则不会在类的方法中剪裁路径。For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. 因此, 路径格式不正确, 并引发异常。Therefore, the path is malformed and an exception is raised. 同样, 路径或路径的组合不能完全限定两次。Similarly, a path or a combination of paths cannot be fully qualified twice. 例如, 在大多数情况下, "c:\temp c:\windows" 也会引发异常。For example, "c:\temp c:\windows" also raises an exception in most cases. 使用接受路径字符串的方法时, 请确保路径格式正确。Ensure that your paths are well-formed when using methods that accept a path string.

在接受路径的成员中, 路径可以引用文件或只引用目录。In members that accept a path, the path can refer to a file or just a directory. 指定的路径还可以引用服务器和共享名称的相对路径或通用命名约定 (UNC) 路径。The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. 例如, 以下所有内容都是可接受的路径:For example, all the following are acceptable paths:

  • Visual Basic 中的\"\c: \MyDir C#\MyFile.txt" 或 "c:\MyDir\MyFile.txt"。"c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.

  • Visual Basic 中的\"c: C#\MyDir" 或 "c:\MyDir"。"c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic.

  • Visual Basic 中\的 "MyDir C#\MySubdir" 或 "MyDir\MySubDir"。"MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in Visual Basic.

  • Visual Basic\中的 "\\ C#\MyServer\\MyShare" 或 "\MyServer\MyShare"。\"\\\\MyServer\\MyShare" in C#, or "\\MyServer\MyShare" in Visual Basic.

FileInfo类提供以下属性, 使您可以检索有关文件的信息。The FileInfo class provides the following properties that enable you to retrieve information about a file. 有关如何使用每个属性的示例, 请参阅属性页。For an example of how to use each property, see the property pages.

  • Directory属性检索对象, 该对象表示文件的父目录。The Directory property retrieves an object that represents the parent directory of a file.

  • DirectoryName属性检索文件的父目录的完整路径。The DirectoryName property retrieves the full path of the parent directory of a file.

  • Exists对文件进行操作之前, 属性会检查该文件是否存在。The Exists property checks for the presence of a file before operating on it.

  • IsReadOnly属性检索或设置一个值, 该值指定是否可以修改文件。The IsReadOnly property retrieves or sets a value that specifies whether a file can be modified.

  • Length检索文件的大小。The Length retrieves the size of a file.

  • Name检索文件的名称。The Name retrieves the name of a file.

构造函数

FileInfo(String)

初始化作为文件路径的包装的 FileInfo 类的新实例。Initializes a new instance of the FileInfo class, which acts as a wrapper for a file path.

字段

FullPath

表示目录或文件的完全限定目录。Represents the fully qualified path of the directory or file.

(继承自 FileSystemInfo)
OriginalPath

最初由用户指定的目录(不论是相对目录还是绝对目录)。The path originally specified by the user, whether relative or absolute.

(继承自 FileSystemInfo)

属性

Attributes

获取或设置当前文件或目录的特性。Gets or sets the attributes for the current file or directory.

(继承自 FileSystemInfo)
CreationTime

获取或设置当前文件或目录的创建时间。Gets or sets the creation time of the current file or directory.

(继承自 FileSystemInfo)
CreationTimeUtc

获取或设置当前文件或目录的创建时间,其格式为协调世界时 (UTC)。Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory.

(继承自 FileSystemInfo)
Directory

获取父目录的实例。Gets an instance of the parent directory.

DirectoryName

获取表示目录的完整路径的字符串。Gets a string representing the directory's full path.

Exists

获取指示文件是否存在的值。Gets a value indicating whether a file exists.

Extension

获取表示文件扩展名部分的字符串。Gets the string representing the extension part of the file.

(继承自 FileSystemInfo)
FullName

获取目录或文件的完整目录。Gets the full path of the directory or file.

(继承自 FileSystemInfo)
IsReadOnly

获取或设置确定当前文件是否为只读的值。Gets or sets a value that determines if the current file is read only.

LastAccessTime

获取或设置上次访问当前文件或目录的时间。Gets or sets the time the current file or directory was last accessed.

(继承自 FileSystemInfo)
LastAccessTimeUtc

获取或设置上次访问当前文件或目录的时间,其格式为协调世界时 (UTC)。Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.

(继承自 FileSystemInfo)
LastWriteTime

获取或设置上次写入当前文件或目录的时间。Gets or sets the time when the current file or directory was last written to.

(继承自 FileSystemInfo)
LastWriteTimeUtc

获取或设置上次写入当前文件或目录的时间,其格式为协调世界时 (UTC)。Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.

(继承自 FileSystemInfo)
Length

获取当前文件的大小(以字节为单位)。Gets the size, in bytes, of the current file.

Name

获取文件名。Gets the name of the file.

方法

AppendText()

创建一个 StreamWriter,它向 FileInfo 的此实例表示的文件追加文本。Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.

CopyTo(String)

将现有文件复制到新文件,不允许覆盖现有文件。Copies an existing file to a new file, disallowing the overwriting of an existing file.

CopyTo(String, Boolean)

将现有文件复制到新文件,允许覆盖现有文件。Copies an existing file to a new file, allowing the overwriting of an existing file.

Create()

创建文件。Creates a file.

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
CreateText()

创建写入新文本文件的 StreamWriterCreates a StreamWriter that writes a new text file.

Decrypt()

使用 Encrypt() 方法解密由当前帐户加密的文件。Decrypts a file that was encrypted by the current account using the Encrypt() method.

Delete()

永久删除文件。Permanently deletes a file.

Encrypt()

将某个文件加密,使得只有加密该文件的帐户才能将其解密。Encrypts a file so that only the account used to encrypt the file can decrypt it.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetAccessControl()

获取 FileSecurity 对象,该对象封装当前 FileInfo 对象所描述的文件的访问控制列表 (ACL) 项。Gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileInfo object.

GetAccessControl(AccessControlSections)

获取一个 FileSecurity 对象,该对象封装当前 FileInfo 对象所描述的文件的指定类型的访问控制列表 (ACL) 项。Gets a FileSecurity object that encapsulates the specified type of access control list (ACL) entries for the file described by the current FileInfo object.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)

设置带有文件名和附加异常信息的 SerializationInfo 对象。Sets the SerializationInfo object with the file name and additional exception information.

(继承自 FileSystemInfo)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
MoveTo(String)

将指定文件移到新位置,提供要指定新文件名的选项。Moves a specified file to a new location, providing the option to specify a new file name.

MoveTo(String, Boolean)

将指定文件移动到新位置,提供指定新文件名和覆盖目标文件(如果它已存在)的选项。Moves a specified file to a new location, providing the options to specify a new file name and to overwrite the destination file if it already exists.

Open(FileMode)

在指定的模式中打开文件。Opens a file in the specified mode.

Open(FileMode, FileAccess)

用读、写或读/写访问权限在指定模式下打开文件。Opens a file in the specified mode with read, write, or read/write access.

Open(FileMode, FileAccess, FileShare)

用读、写或读/写访问权限和指定的共享选项在指定的模式中打开文件。Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.

OpenRead()

创建一个只读的 FileStreamCreates a read-only FileStream.

OpenText()

创建使用从现有文本文件中读取的 UTF8 编码的 StreamReaderCreates a StreamReader with UTF8 encoding that reads from an existing text file.

OpenWrite()

创建一个只写的 FileStreamCreates a write-only FileStream.

Refresh()

刷新对象的状态。Refreshes the state of the object.

(继承自 FileSystemInfo)
Replace(String, String)

使用当前 FileInfo 对象所描述的文件替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份。Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file.

Replace(String, String, Boolean)

使用当前 FileInfo 对象所描述的文件替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份。Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file. 还指定是否忽略合并错误。Also specifies whether to ignore merge errors.

SetAccessControl(FileSecurity)

FileSecurity 对象所描述的访问控制列表 (ACL) 项应用于当前 FileInfo 对象所描述的文件。Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileInfo object.

ToString()

以字符串形式返回路径。Returns the path as a string. Name 属性用于完整路径。Use the Name property for the full path.

扩展方法

GetAccessControl(FileInfo)
GetAccessControl(FileInfo, AccessControlSections)
SetAccessControl(FileInfo, FileSecurity)

适用于

另请参阅