如何:將文字寫入至檔案
本文會示範 .NET 應用程式將文字寫入檔案的不同方式。
通常會使用下列類別和方法,將文字寫入至檔案:
StreamWriter 包含同步 (Write 和 WriteLine) 或非同步 (WriteAsync 和 WriteLineAsync) 寫入檔案的方法。
File 所提供的靜態方法可將文字寫入檔案 (例如 WriteAllLines 和 WriteAllText),或將文字附加至檔案 (例如 AppendAllLines、AppendAllText 或 AppendText)。
Path 適用於含有檔案或目錄路徑資訊的字串。 其包含 Combine 方法和 .NET Core 2.1 和更新版本中的 Join 和 TryJoin 方法。 這些方法可讓您串連用來建置檔案或目錄路徑的字串。
注意
下列範例只顯示所需的最少數量程式碼。 真實世界應用程式通常會提供更強大的錯誤檢查和例外狀況處理。
範例:使用 StreamWriter 同步寫入文字
下列範例示範如何使用 StreamWriter 類別,以同步方式一次一行將文字寫入新檔案。 由於 StreamWriter 物件是在 using
陳述式中宣告及具現化,因此會叫用 Dispose 方法,其會自動排清並關閉資料流。
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Create a string array with the lines of text
string[] lines = { "First line", "Second line", "Third line" };
// Set a variable to the Documents path.
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the string array to a new file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
}
}
// The example creates a file named "WriteLines.txt" with the following contents:
// First line
// Second line
// Third line
Imports System.IO
Class WriteText
Public Shared Sub Main()
' Create a string array with the lines of text
Dim lines() As String = {"First line", "Second line", "Third line"}
' Set a variable to the Documents path.
Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
' Write the string array to a new file named "WriteLines.txt".
Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt")))
For Each line As String In lines
outputFile.WriteLine(line)
Next
End Using
End Sub
End Class
' The example creates a file named "WriteLines.txt" with the following contents:
' First line
' Second line
' Third line
範例:使用 StreamWriter 同步附加文字
下列範例示範如何使用 StreamWriter 類別,以同步方式將文字附加至第一個範例中建立的文字檔:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Set a variable to the Documents path.
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Append text to an existing file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine("Fourth Line");
}
}
}
// The example adds the following line to the contents of "WriteLines.txt":
// Fourth Line
Imports System.IO
Class AppendText
Public Shared Sub Main()
' Set a variable to the Documents path.
Dim docPath As String =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
' Append text to an existing file named "WriteLines.txt".
Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt")), True)
outputFile.WriteLine("Fourth Line")
End Using
End Sub
End Class
' The example adds the following line to the contents of "WriteLines.txt":
' Fourth Line
範例:使用 StreamWriter 同步寫入文字
下列範例示範如何使用 StreamWriter 類別,以非同步方式將文字寫入至新檔案。 若要叫用 WriteAsync 方法,必須在 async
方法中呼叫此方法。
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// Set a variable to the Documents path.
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the specified text asynchronously to a new file named "WriteTextAsync.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteTextAsync.txt")))
{
await outputFile.WriteAsync("This is a sentence.");
}
}
}
// The example creates a file named "WriteTextAsync.txt" with the following contents:
// This is a sentence.
Imports System.IO
Public Module Example
Public Sub Main()
WriteTextAsync()
End Sub
Async Sub WriteTextAsync()
' Set a variable to the Documents path.
Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
' Write the text asynchronously to a new file named "WriteTextAsync.txt".
Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteTextAsync.txt")))
Await outputFile.WriteAsync("This is a sentence.")
End Using
End Sub
End Module
' The example creates a file named "WriteTextAsync.txt" with the following contents:
' This is a sentence.
範例:使用 File 類別寫入和附加文字
下列範例示範如何使用 File 類別,將文字寫入至新檔案,並將新的文字行附加至相同的檔案。 WriteAllText 和 AppendAllLines 方法會自動開啟和關閉檔案。 如果提供給 WriteAllText 方法的路徑已經存在,則會覆寫該檔案。
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Create a string with a line of text.
string text = "First line" + Environment.NewLine;
// Set a variable to the Documents path.
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the text to a new file named "WriteFile.txt".
File.WriteAllText(Path.Combine(docPath, "WriteFile.txt"), text);
// Create a string array with the additional lines of text
string[] lines = { "New line 1", "New line 2" };
// Append new lines of text to the file
File.AppendAllLines(Path.Combine(docPath, "WriteFile.txt"), lines);
}
}
// The example creates a file named "WriteFile.txt" with the contents:
// First line
// And then appends the following contents:
// New line 1
// New line 2
Imports System.IO
Class WriteFile
Public Shared Sub Main()
' Create a string array with the lines of text
Dim text As String = "First line" & Environment.NewLine
' Set a variable to the Documents path.
Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
' Write the text to a new file named "WriteFile.txt".
File.WriteAllText(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), text)
' Create a string array with the additional lines of text
Dim lines() As String = {"New line 1", "New line 2"}
' Append new lines of text to the file
File.AppendAllLines(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), lines)
End Sub
End Class
' The example creates a file named "WriteFile.txt" with the following contents:
' First line
' And then appends the following contents:
' New line 1
' New line 2