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.

第一次擷取屬性,當FileInfo呼叫Refresh方法和快取檔案的相關資訊。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();
        FileInfo 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()) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }

        try 
        {
            string path2 = Path.GetTempFileName();
            FileInfo fi2 = new 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.ToString());
        }
    }
}
Imports System
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 FileInfo = New FileInfo(path1)

        'Create a file to write to.
        Dim sw As StreamWriter = fi.CreateText()

        sw.WriteLine("Hello")
        sw.WriteLine("And")
        sw.WriteLine("Welcome")
        sw.Flush()
        sw.Close()

        Try
            'Open the file to read from.
            Dim sr As StreamReader = fi.OpenText()

            Do While sr.Peek() >= 0
                Console.WriteLine(sr.ReadLine())
            Loop
            sr.Close()
            Dim fi2 As FileInfo = New FileInfo(path2)

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

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

            'Delete the newly created file.
            fi2.Delete()
            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

此範例會產生類似下列的輸出。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這類成員OpenOpenReadOpenTextCreateText,或CreateFor 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:

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

  • "c:\\MyDir 」 以 C# 或 Visual Basic 中的 「 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.

  • 「\\\\MyServer\\MyShare 」 在 C# 中,或 「\\MyServer\MyShare"在 Visual Basic 中。"\\\\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 的淺層複製。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)
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.

欄位

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)

Extension Methods

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)

適用於

另請參閱