共用方式為


File 類別

定義

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

public ref class File abstract sealed
public ref class File sealed
public static class File
public sealed class File
[System.Runtime.InteropServices.ComVisible(true)]
public static class File
type File = class
[<System.Runtime.InteropServices.ComVisible(true)>]
type File = class
Public Class File
Public NotInheritable Class File
繼承
File
屬性

範例

下列範例示範如何使用 File 類別來檢查檔案是否存在,並根據結果,建立新的檔案並寫入檔案,或開啟現有的檔案並從中讀取。 在執行程式代碼之前,請先建立 c:\temp 資料夾。

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 );
   }
}
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);
            }
        }
    }
}
open System.IO

let path = @"c:\temp\MyTest.txt"

if File.Exists path |> not then
    // Create a file to write to.
    use sw = File.CreateText path
    sw.WriteLine "Hello"
    sw.WriteLine "And"
    sw.WriteLine "Welcome"

// Open the file to read from.
do
    use sr = File.OpenText path
    let mutable s = sr.ReadLine()

    while isNull s |> not do
        printfn $"{s}"
        s <- sr.ReadLine()
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.
            Using sw As StreamWriter = File.CreateText(path)
                sw.WriteLine("Hello")
                sw.WriteLine("And")
                sw.WriteLine("Welcome")
           End Using
        End If

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

備註

針對一般作業使用 File 類別,例如一次複製、移動、重新命名、建立、開啟、刪除和附加至單一檔案。 您也可以使用 File 類別來取得和設定檔案屬性,或 DateTime 與建立、存取和寫入檔案相關的資訊。 如果您要對多個檔案執行作業,請參閱 Directory.GetFilesDirectoryInfo.GetFiles

當您建立或開啟檔案時,許多 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 工作的清單,請參閱 一般 I/O 工作

方法

AppendAllBytes(String, Byte[])

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

AppendAllBytes(String, ReadOnlySpan<Byte>)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

AppendAllBytesAsync(String, Byte[], CancellationToken)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

AppendAllBytesAsync(String, ReadOnlyMemory<Byte>, CancellationToken)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

AppendAllLines(String, IEnumerable<String>)

將行附加至檔案,然後關閉檔案。 如果指定的檔案不存在,這個方法會建立檔案、將指定的行寫入檔案,然後關閉檔案。

AppendAllLines(String, IEnumerable<String>, Encoding)

使用指定的編碼將行附加至檔案,然後關閉檔案。 如果指定的檔案不存在,這個方法會建立檔案、將指定的行寫入檔案,然後關閉檔案。

AppendAllLinesAsync(String, IEnumerable<String>, CancellationToken)

以異步方式將行附加至檔案,然後關閉檔案。 如果指定的檔案不存在,這個方法會建立檔案、將指定的行寫入檔案,然後關閉檔案。

AppendAllLinesAsync(String, IEnumerable<String>, Encoding, CancellationToken)

使用指定的編碼,以異步方式將行附加至檔案,然後關閉檔案。 如果指定的檔案不存在,這個方法會建立檔案、將指定的行寫入檔案,然後關閉檔案。

AppendAllText(String, ReadOnlySpan<Char>)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

AppendAllText(String, ReadOnlySpan<Char>, Encoding)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

AppendAllText(String, String)

開啟檔案、將指定的字串附加至檔案,然後關閉檔案。 如果檔案不存在,這個方法會建立檔案、將指定的字串寫入檔案,然後關閉檔案。

AppendAllText(String, String, Encoding)

使用指定的編碼將指定的字串附加至檔案,如果檔案不存在,則建立檔案。

AppendAllTextAsync(String, ReadOnlyMemory<Char>, CancellationToken)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

AppendAllTextAsync(String, ReadOnlyMemory<Char>, Encoding, CancellationToken)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

AppendAllTextAsync(String, String, CancellationToken)

以異步方式開啟檔案,或在檔案不存在時建立檔案、將指定的字串附加至檔案,然後關閉檔案。

AppendAllTextAsync(String, String, Encoding, CancellationToken)

以異步方式開啟檔案,或在檔案不存在時建立檔案、使用指定的編碼將指定的字串附加至檔案,然後關閉檔案。

AppendText(String)

建立一個 StreamWriter,將UTF-8編碼的文字附加至現有的檔案,或如果指定的檔案不存在,則附加至新的檔案。

Copy(String, String)

將現有的檔案複製到新的檔案。 不允許覆寫同名的檔案。

Copy(String, String, Boolean)

將現有的檔案複製到新的檔案。 允許覆寫相同名稱的檔案。

Create(String)

建立或截斷並覆寫指定路徑中的檔案。

Create(String, Int32)

建立或截斷並覆寫指定路徑中的檔案,並指定緩衝區大小。

Create(String, Int32, FileOptions)

在指定的路徑中建立或覆寫檔案,並指定緩衝區大小和描述如何建立或覆寫檔案的選項。

Create(String, Int32, FileOptions, FileSecurity)

在指定的路徑中建立或覆寫檔案、指定緩衝區大小、描述如何建立或覆寫檔案的選項,以及決定檔案訪問控制和稽核安全性的值。

CreateSymbolicLink(String, String)

建立指向 pathToTargetpath 所識別的檔案符號連結。

CreateText(String)

建立或開啟用來寫入UTF-8編碼文字的檔案。 如果檔案已經存在,則會取代其內容。

Decrypt(String)

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

Delete(String)

刪除指定的檔案。

Encrypt(String)

加密檔案,讓只有用來加密檔案的帳戶才能解密它。

Exists(String)

判斷指定的檔案是否存在。

GetAccessControl(String)

取得 FileSecurity 對象,這個物件會封裝指定檔案的訪問控制清單 (ACL) 專案。

GetAccessControl(String, AccessControlSections)

取得 FileSecurity 物件,該物件會封裝特定檔案的指定訪問控制清單 (ACL) 項目類型。

GetAttributes(SafeFileHandle)

取得與 fileHandle相關聯之檔案或目錄的指定 FileAttributes

GetAttributes(String)

取得路徑上檔案的 FileAttributes

GetCreationTime(SafeFileHandle)

傳回指定檔案或目錄的建立時間。

GetCreationTime(String)

傳回指定檔案或目錄的建立日期和時間。

GetCreationTimeUtc(SafeFileHandle)

傳回指定檔案或目錄之國際標準時間 (UTC) 的建立日期和時間。

GetCreationTimeUtc(String)

傳回指定檔案或目錄之國際標準時間 (UTC) 的建立日期和時間。

GetLastAccessTime(SafeFileHandle)

傳回指定檔案或目錄的最後存取日期和時間。

GetLastAccessTime(String)

傳回上次存取指定檔案或目錄的日期和時間。

GetLastAccessTimeUtc(SafeFileHandle)

傳回指定之檔案或目錄的最後一個存取日期和時間,以國際標準時間 (UTC) 為單位。

GetLastAccessTimeUtc(String)

以國際標準時間 (UTC) 傳回上次存取指定檔案或目錄的日期和時間。

GetLastWriteTime(SafeFileHandle)

傳回指定之檔案或目錄的最後寫入日期和時間。

GetLastWriteTime(String)

傳回指定檔案或目錄上次寫入的日期和時間。

GetLastWriteTimeUtc(SafeFileHandle)

傳回指定之檔案或目錄的最後一個寫入日期和時間,以國際標準時間 (UTC) 為單位。

GetLastWriteTimeUtc(String)

以國際標準時間 (UTC) 傳回指定檔案或目錄上次寫入的日期和時間。

GetUnixFileMode(SafeFileHandle)

取得指定之檔句柄的 UnixFileMode

GetUnixFileMode(String)

取得路徑上檔案的 UnixFileMode

Move(String, String)

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

Move(String, String, Boolean)

將指定的檔案移至新位置,並提供選項來指定新的檔名,並在目的地檔案已經存在時取代目的地檔案。

Open(String, FileMode)

在具有讀取/寫入存取權且不共用的指定路徑上開啟 FileStream

Open(String, FileMode, FileAccess)

在指定的路徑上開啟 FileStream,並以指定的模式和沒有共用的存取權。

Open(String, FileMode, FileAccess, FileShare)

在指定的路徑上開啟 FileStream,具有具有讀取、寫入或讀取/寫入存取權和指定共用選項的指定模式。

Open(String, FileStreamOptions)

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

OpenHandle(String, FileMode, FileAccess, FileShare, FileOptions, Int64)

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

OpenRead(String)

開啟現有的檔案以供讀取。

OpenText(String)

開啟現有的 UTF-8 編碼文字檔以供讀取。

OpenWrite(String)

開啟現有的檔案,或建立新的檔案以供寫入。

ReadAllBytes(String)

開啟二進位檔,將檔案的內容讀入位元組陣列,然後關閉檔案。

ReadAllBytesAsync(String, CancellationToken)

以異步方式開啟二進位檔,將檔案的內容讀入位元組陣列,然後關閉檔案。

ReadAllLines(String)

開啟文字文件、讀取檔案的所有行,然後關閉檔案。

ReadAllLines(String, Encoding)

開啟檔案、使用指定的編碼讀取檔案的所有行,然後關閉檔案。

ReadAllLinesAsync(String, CancellationToken)

以異步方式開啟文本文件、讀取檔案的所有行,然後關閉檔案。

ReadAllLinesAsync(String, Encoding, CancellationToken)

以異步方式開啟文本檔、使用指定的編碼讀取檔案的所有行,然後關閉檔案。

ReadAllText(String)

開啟文字文件、讀取檔案中的所有文字,然後關閉檔案。

ReadAllText(String, Encoding)

開啟檔案,以指定的編碼方式讀取檔案中的所有文字,然後關閉檔案。

ReadAllTextAsync(String, CancellationToken)

以異步方式開啟文本文件、讀取檔案中的所有文字,然後關閉檔案。

ReadAllTextAsync(String, Encoding, CancellationToken)

以異步方式開啟文本檔、使用指定的編碼讀取檔案中的所有文字,然後關閉檔案。

ReadLines(String)

讀取檔案的行。

ReadLines(String, Encoding)

讀取具有指定編碼方式的檔案行。

ReadLinesAsync(String, CancellationToken)

以異步方式讀取檔案的行。

ReadLinesAsync(String, Encoding, CancellationToken)

以異步方式讀取具有指定編碼的檔案行。

Replace(String, String, String)

將指定檔案的內容取代為另一個檔案的內容、刪除源檔,以及建立已取代檔案的備份。

Replace(String, String, String, Boolean)

將指定檔案的內容取代為另一個檔案的內容、刪除源檔並建立已取代檔案的備份,並選擇性地忽略合併錯誤。

ResolveLinkTarget(String, Boolean)

取得指定檔案鏈接的目標。

SetAccessControl(String, FileSecurity)

FileSecurity 物件描述的訪問控制清單 (ACL) 專案套用至指定的檔案。

SetAttributes(SafeFileHandle, FileAttributes)

設定與 fileHandle相關聯之檔案或目錄的指定 FileAttributes

SetAttributes(String, FileAttributes)

設定指定路徑上檔案的指定 FileAttributes

SetCreationTime(SafeFileHandle, DateTime)

設定建立檔案或目錄的日期和時間。

SetCreationTime(String, DateTime)

設定檔案建立的日期和時間。

SetCreationTimeUtc(SafeFileHandle, DateTime)

以國際標準時間設定建立檔案或目錄的日期和時間。

SetCreationTimeUtc(String, DateTime)

以國際標準時間 (UTC) 設定檔案建立的日期和時間。

SetLastAccessTime(SafeFileHandle, DateTime)

設定上次存取指定檔案或目錄的日期和時間。

SetLastAccessTime(String, DateTime)

設定上次存取指定檔案的日期和時間。

SetLastAccessTimeUtc(SafeFileHandle, DateTime)

以國際標準時間 (UTC) 設定上次存取指定檔案或目錄的日期和時間。

SetLastAccessTimeUtc(String, DateTime)

以國際標準時間 (UTC) 設定上次存取指定檔案的日期和時間。

SetLastWriteTime(SafeFileHandle, DateTime)

設定指定檔案或目錄上次寫入的日期和時間。

SetLastWriteTime(String, DateTime)

設定指定檔案上次寫入的日期和時間。

SetLastWriteTimeUtc(SafeFileHandle, DateTime)

以國際標準時間 (UTC) 設定指定檔案或目錄上次寫入的日期和時間。

SetLastWriteTimeUtc(String, DateTime)

以國際標準時間 (UTC) 設定指定檔案上次寫入的日期和時間。

SetUnixFileMode(SafeFileHandle, UnixFileMode)

設定指定之檔句柄的指定 UnixFileMode

SetUnixFileMode(String, UnixFileMode)

設定指定路徑上檔案的指定 UnixFileMode

WriteAllBytes(String, Byte[])

建立新的檔案、將指定的位元組數位組寫入檔案,然後關閉檔案。 如果目標檔案已經存在,則會遭到截斷並覆寫。

WriteAllBytes(String, ReadOnlySpan<Byte>)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

WriteAllBytesAsync(String, Byte[], CancellationToken)

以異步方式建立新的檔案、將指定的位元組陣組寫入檔案,然後關閉檔案。 如果目標檔案已經存在,則會遭到截斷並覆寫。

WriteAllBytesAsync(String, ReadOnlyMemory<Byte>, CancellationToken)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

WriteAllLines(String, IEnumerable<String>)

建立新的檔案、將字串集合寫入檔案,然後關閉檔案。

WriteAllLines(String, IEnumerable<String>, Encoding)

使用指定的編碼方式建立新的檔案、將字串集合寫入檔案,然後關閉檔案。

WriteAllLines(String, String[])

建立新的檔案、將指定的字串數位寫入檔案,然後關閉檔案。

WriteAllLines(String, String[], Encoding)

建立新的檔案、使用指定的編碼將指定的字串陣列寫入檔案,然後關閉檔案。

WriteAllLinesAsync(String, IEnumerable<String>, CancellationToken)

以異步方式建立新的檔案、將指定的行寫入檔案,然後關閉檔案。

WriteAllLinesAsync(String, IEnumerable<String>, Encoding, CancellationToken)

以異步方式建立新的檔案、使用指定的編碼方式將指定的行寫入檔案,然後關閉檔案。

WriteAllText(String, ReadOnlySpan<Char>)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

WriteAllText(String, ReadOnlySpan<Char>, Encoding)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

WriteAllText(String, String)

建立新的檔案、將指定的字串寫入檔案,然後關閉檔案。 如果目標檔案已經存在,則會遭到截斷並覆寫。

WriteAllText(String, String, Encoding)

建立新的檔案、使用指定的編碼將指定的字串寫入檔案,然後關閉檔案。 如果目標檔案已經存在,則會遭到截斷並覆寫。

WriteAllTextAsync(String, ReadOnlyMemory<Char>, CancellationToken)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

WriteAllTextAsync(String, ReadOnlyMemory<Char>, Encoding, CancellationToken)

提供靜態方法來建立、複製、刪除、移動和開啟單一檔案,並協助建立 FileStream 物件。

WriteAllTextAsync(String, String, CancellationToken)

以異步方式建立新的檔案、將指定的字串寫入檔案,然後關閉檔案。 如果目標檔案已經存在,則會遭到截斷並覆寫。

WriteAllTextAsync(String, String, Encoding, CancellationToken)

以異步方式建立新的檔案、使用指定的編碼將指定的字串寫入檔案,然後關閉檔案。 如果目標檔案已經存在,則會遭到截斷並覆寫。

適用於

另請參閱