FileInfo FileInfo FileInfo FileInfo Class

定義

提供建立、複製、刪除、移動和開啟檔案的屬性和執行個體方法,並協助建立 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參閱特定成員Open, OpenRead例如OpenTextCreateText、、 Create或。For 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#的\"c: \MyDir \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.

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

  • 中\的 "\ C#\MyServer \MyShare", 或\Visual Basic 中的 "\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(String) FileInfo(String) FileInfo(String)

初始化 FileInfo 類別的新執行個體,以做為檔案路徑的包裝函式。Initializes a new instance of the FileInfo class, which acts as a wrapper for a file path.

屬性

Attributes Attributes Attributes Attributes

取得或設定目前檔案或目錄的屬性。Gets or sets the attributes for the current file or directory.

(Inherited from FileSystemInfo)
CreationTime CreationTime CreationTime CreationTime

取得或設定目前檔案或目錄的建立時間。Gets or sets the creation time of the current file or directory.

(Inherited from FileSystemInfo)
CreationTimeUtc CreationTimeUtc CreationTimeUtc CreationTimeUtc

取得或設定目前檔案或目錄的建立時間,其格式為國際標準時間 (Coordinated Universal Time,UTC)。Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory.

(Inherited from FileSystemInfo)
Directory Directory Directory Directory

取得父代 (Parent) 目錄的執行個體。Gets an instance of the parent directory.

DirectoryName DirectoryName DirectoryName DirectoryName

取得表示目錄完整路徑的字串。Gets a string representing the directory's full path.

Exists Exists Exists Exists

取得值,這個值指出檔案是否存在。Gets a value indicating whether a file exists.

Extension Extension Extension Extension

取得字串,表示檔案的副檔名部分。Gets the string representing the extension part of the file.

(Inherited from FileSystemInfo)
FullName FullName FullName FullName

取得目錄或檔案的完整路徑。Gets the full path of the directory or file.

(Inherited from FileSystemInfo)
IsReadOnly IsReadOnly IsReadOnly IsReadOnly

取得或設定值,判斷目前檔案是否為唯讀。Gets or sets a value that determines if the current file is read only.

LastAccessTime LastAccessTime LastAccessTime LastAccessTime

取得或設定上次存取目前檔案或目錄的時間。Gets or sets the time the current file or directory was last accessed.

(Inherited from FileSystemInfo)
LastAccessTimeUtc LastAccessTimeUtc LastAccessTimeUtc LastAccessTimeUtc

取得或設定目前檔案或目錄上次被存取的時間,其格式為 Coordinated Universal Time (UTC)。Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.

(Inherited from FileSystemInfo)
LastWriteTime LastWriteTime LastWriteTime LastWriteTime

取得或設定上次寫入目前檔案或目錄的時間。Gets or sets the time when the current file or directory was last written to.

(Inherited from FileSystemInfo)
LastWriteTimeUtc LastWriteTimeUtc LastWriteTimeUtc LastWriteTimeUtc

取得或設定目前檔案或目錄上次被寫入的時間,其格式為 Coordinated Universal Time (UTC)。Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.

(Inherited from FileSystemInfo)
Length Length Length Length

取得目前檔案的大小,以位元組為單位。Gets the size, in bytes, of the current file.

Name Name Name Name

取得檔案的名稱。Gets the name of the file.

方法

AppendText() AppendText() AppendText() AppendText()

建立將文字附加在 StreamWriter 的這個執行個體所表示之檔案的 FileInfoCreates a StreamWriter that appends text to the file represented by this instance of the FileInfo.

CopyTo(String) CopyTo(String) CopyTo(String) CopyTo(String)

複製現有的檔案到新的檔案,不允許覆寫現有的檔案。Copies an existing file to a new file, disallowing the overwriting of an existing file.

CopyTo(String, Boolean) CopyTo(String, Boolean) CopyTo(String, Boolean) CopyTo(String, Boolean)

複製現有的檔案到新檔案,允許覆寫現有的檔案。Copies an existing file to a new file, allowing the overwriting of an existing file.

Create() Create() Create() Create()

建立檔案。Creates a file.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateText() CreateText() CreateText() CreateText()

建立寫入新文字檔的 StreamWriterCreates a StreamWriter that writes a new text file.

Decrypt() Decrypt() Decrypt() Decrypt()

解密目前帳戶使用 Encrypt() 方法加密的檔案。Decrypts a file that was encrypted by the current account using the Encrypt() method.

Delete() Delete() Delete() Delete()

永遠地刪除檔案。Permanently deletes a file.

Encrypt() Encrypt() Encrypt() Encrypt()

加密檔案,只有使用加密檔案的帳戶才能將其解密。Encrypts a file so that only the account used to encrypt the file can decrypt it.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetAccessControl() GetAccessControl() GetAccessControl() 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) GetAccessControl(AccessControlSections) GetAccessControl(AccessControlSections) 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() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

以檔案名稱和其他例外狀況資訊設定 SerializationInfo 物件。Sets the SerializationInfo object with the file name and additional exception information.

(Inherited from FileSystemInfo)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
MoveTo(String) MoveTo(String) MoveTo(String) MoveTo(String)

移動指定的檔案至新的位置,提供指定新檔名的選項。Moves a specified file to a new location, providing the option to specify a new file name.

MoveTo(String, Boolean) MoveTo(String, Boolean) MoveTo(String, Boolean) 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) Open(FileMode) Open(FileMode) Open(FileMode)

使用指定模式來開啟檔案。Opens a file in the specified mode.

Open(FileMode, FileAccess) Open(FileMode, FileAccess) Open(FileMode, FileAccess) Open(FileMode, FileAccess)

使用讀取、寫入或讀取/寫入存取,並以指定模式來開啟檔案。Opens a file in the specified mode with read, write, or read/write access.

Open(FileMode, FileAccess, FileShare) Open(FileMode, FileAccess, FileShare) Open(FileMode, FileAccess, FileShare) Open(FileMode, FileAccess, FileShare)

使用讀取、寫入或讀取/寫入存取和指定的共用選項,將檔案開啟於指定模式中。Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.

OpenRead() OpenRead() OpenRead() OpenRead()

建立唯讀的 FileStreamCreates a read-only FileStream.

OpenText() OpenText() OpenText() OpenText()

建立從現有文字檔讀取的 StreamReader (具有 UTF8 編碼方式)。Creates a StreamReader with UTF8 encoding that reads from an existing text file.

OpenWrite() OpenWrite() OpenWrite() OpenWrite()

建立唯寫的 FileStreamCreates a write-only FileStream.

Refresh() Refresh() Refresh() Refresh()

重新整理物件的狀態。Refreshes the state of the object.

(Inherited from FileSystemInfo)
Replace(String, String) Replace(String, String) Replace(String, String) 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) Replace(String, String, Boolean) Replace(String, String, Boolean) 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) SetAccessControl(FileSecurity) SetAccessControl(FileSecurity) 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() ToString() ToString() ToString()

將路徑當做字串傳回。Returns the path as a string. 使用 Name 屬性作為完整路徑。Use the Name property for the full path.

欄位

FullPath FullPath FullPath FullPath

表示目錄或檔案的完整路徑。Represents the fully qualified path of the directory or file.

(Inherited from FileSystemInfo)
OriginalPath OriginalPath OriginalPath OriginalPath

使用者指定的相對或絕對的原始路徑。The path originally specified by the user, whether relative or absolute.

(Inherited from FileSystemInfo)

擴充方法

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

適用於

另請參閱