如何:将文本写入文件
本文介绍将文本写入 .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 类将文本写入新文件并将新的文本行追加到同一文件。 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