FileInfo 類別

定義

提供建立、複製、刪除、移動和開啟檔案的屬性和執行個體方法,並協助建立 FileStream 物件。 此類別無法獲得繼承。

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

範例

下列範例示範 類別的 FileInfo 一些主要成員。

第一次擷取屬性時, FileInfo 呼叫 Refresh 方法並快取檔案的相關資訊。 在後續的呼叫中,您必須呼叫 Refresh 以取得資訊的最新複本。

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

此範例會產生類似下列的輸出。

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 一般作業使用 類別,例如複製、移動、重新命名、建立、開啟、刪除和附加至檔案。

如果您要在同一個檔案上執行多個作業,則使用 FileInfo 實例方法而不是 類別的 File 對應靜態方法會更有效率,因為安全性檢查不一定是必要的。

當您建立或開啟檔案時, FileInfo 許多方法都會傳回其他 I/O 類型。 您可以使用這些其他類型的來進一步操作檔案。 如需詳細資訊,請參閱特定 FileInfo 成員,例如 OpenOpenReadOpenTextCreateTextCreate

根據預設,會將新檔案的完整讀取/寫入權限授與所有使用者。

下表描述用來自訂各種 FileInfo 方法行為的列舉。

列舉型別 描述
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」。

類別 FileInfo 提供下列屬性,可讓您擷取檔案的相關資訊。 如需如何使用每個屬性的範例,請參閱屬性頁。

  • 屬性會 Directory 擷取代表檔案之父目錄的物件。

  • 屬性 DirectoryName 會擷取檔案之父目錄的完整路徑。

  • 屬性 Exists 會先檢查檔案是否存在,再加以操作。

  • 屬性 IsReadOnly 會擷取或設定值,指定是否可以修改檔案。

  • Length 擷取檔案的大小。

  • Name 擷取檔案名。

建構函式

FileInfo(String)

初始化 FileInfo 類別的新執行個體,以做為檔案路徑的包裝函式。

欄位

FullPath

表示目錄或檔案的完整路徑。

(繼承來源 FileSystemInfo)
OriginalPath

使用者指定的相對或絕對的原始路徑。

(繼承來源 FileSystemInfo)

屬性

Attributes

取得或設定目前檔案或目錄的屬性。

(繼承來源 FileSystemInfo)
CreationTime

取得或設定目前檔案或目錄的建立時間。

(繼承來源 FileSystemInfo)
CreationTimeUtc

取得或設定目前檔案或目錄的建立時間,其格式為國際標準時間 (Coordinated Universal Time,UTC)。

(繼承來源 FileSystemInfo)
Directory

取得父代 (Parent) 目錄的執行個體。

DirectoryName

取得表示目錄完整路徑的字串。

Exists

取得值,這個值指出檔案是否存在。

Extension

取得檔案名的副檔名部分,包括前置點 . ,即使它是整個檔案名,或是沒有副檔名則為空字串。

(繼承來源 FileSystemInfo)
FullName

取得目錄或檔案的完整路徑。

(繼承來源 FileSystemInfo)
IsReadOnly

取得或設定值,判斷目前檔案是否為唯讀。

LastAccessTime

取得或設定上次存取目前檔案或目錄的時間。

(繼承來源 FileSystemInfo)
LastAccessTimeUtc

取得或設定目前檔案或目錄上次被存取的時間,其格式為 Coordinated Universal Time (UTC)。

(繼承來源 FileSystemInfo)
LastWriteTime

取得或設定上次寫入目前檔案或目錄的時間。

(繼承來源 FileSystemInfo)
LastWriteTimeUtc

取得或設定目前檔案或目錄上次被寫入的時間,其格式為 Coordinated Universal Time (UTC)。

(繼承來源 FileSystemInfo)
Length

取得目前檔案的大小,以位元組為單位。

LinkTarget

取得位於 中 FullName 之連結的目標路徑,如果這個實例不代表連結,則 nullFileSystemInfo

(繼承來源 FileSystemInfo)
Name

取得檔案的名稱。

UnixFileMode

取得或設定目前檔案或目錄的 Unix 檔案模式。

(繼承來源 FileSystemInfo)

方法

AppendText()

建立將文字附加在 StreamWriter 的這個執行個體所表示之檔案的 FileInfo

CopyTo(String)

複製現有的檔案到新的檔案,不允許覆寫現有的檔案。

CopyTo(String, Boolean)

複製現有的檔案到新檔案,允許覆寫現有的檔案。

Create()

建立檔案。

CreateAsSymbolicLink(String)

建立位於 的 FullName 符號連結,指向指定的 pathToTarget

(繼承來源 FileSystemInfo)
CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
CreateText()

建立寫入新文字檔的 StreamWriter

Decrypt()

解密目前帳戶使用 Encrypt() 方法加密的檔案。

Delete()

永遠地刪除檔案。

Encrypt()

加密檔案,只有使用加密檔案的帳戶才能將其解密。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetAccessControl()

取得 FileSecurity 物件,該物件會封裝目前 FileInfo 物件所描述的檔案之存取控制清單 (ACL) 項目。

GetAccessControl(AccessControlSections)

取得 FileSecurity 物件,該物件會封裝目前 FileInfo 物件所描述的檔案之指定類型的存取控制清單 (ACL) 項目。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)

以檔案名稱和其他例外狀況資訊設定 SerializationInfo 物件。

(繼承來源 FileSystemInfo)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
InitializeLifetimeService()
已淘汰.

取得存留期服務物件,以控制這個執行個體的存留期原則。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。

(繼承來源 MarshalByRefObject)
MoveTo(String)

移動指定的檔案至新的位置,提供指定新檔名的選項。

MoveTo(String, Boolean)

將指定的檔案移至新位置,提供可指定新檔案名稱的選項,並覆寫目的地檔案 (如果已存在)。

Open(FileMode)

使用指定模式來開啟檔案。

Open(FileMode, FileAccess)

使用讀取、寫入或讀取/寫入存取,並以指定模式來開啟檔案。

Open(FileMode, FileAccess, FileShare)

使用讀取、寫入或讀取/寫入存取和指定的共用選項,將檔案開啟於指定模式中。

Open(FileStreamOptions)

使用指定的建立模式、讀取/寫入和共用許可權,初始化 類別的新實例 FileStream ,其他 FileStreams 的存取權可以相同檔案、緩衝區大小、其他檔案選項和配置大小。

OpenRead()

建立唯讀的 FileStream

OpenText()

建立從現有文字檔讀取的 StreamReader (具有 UTF8 編碼方式)。

OpenWrite()

建立唯寫的 FileStream

Refresh()

重新整理物件的狀態。

(繼承來源 FileSystemInfo)
Replace(String, String)

以目前 FileInfo 物件所描述的檔案,取代指定檔案的內容、刪除原始檔案,並建立已取代檔案的備份。

Replace(String, String, Boolean)

以目前 FileInfo 物件所描述的檔案,取代指定檔案的內容、刪除原始檔案,並建立已取代檔案的備份。 該方法還指定是否忽略合併錯誤。

ResolveLinkTarget(Boolean)

取得指定連結的目標。

(繼承來源 FileSystemInfo)
SetAccessControl(FileSecurity)

FileSecurity 物件所描述的存取控制清單 (ACL) 項目套用至目前 FileInfo 物件所描述的檔案。

ToString()

將路徑當做字串傳回。 使用 Name 屬性作為完整路徑。

ToString()

傳回原始路徑。 使用 FullNameName 屬性作為完整路徑或檔案/目錄名稱。

(繼承來源 FileSystemInfo)

擴充方法

Create(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)

建立新的檔案資料流,確保其以指定的屬性和安全性設定所建立。

GetAccessControl(FileInfo)

傳回檔案的安全性資訊。

GetAccessControl(FileInfo, AccessControlSections)

傳回檔案的安全性資訊。

SetAccessControl(FileInfo, FileSecurity)

變更現有檔案的安全性屬性。

適用於

另請參閱