Vorgehensweise: Schreiben von Text in eine DateiHow to: Write text to a file
In diesem Artikel werden verschiedene Vorgehensweisen zum Schreiben von Text in eine Datei für eine .NET-Anwendung veranschaulicht.This topic shows different ways to write text to a file for a .NET app.
Die folgenden Klassen und Methoden werden in der Regel zum Schreiben von Text in eine Datei verwendet:The following classes and methods are typically used to write text to a file:
StreamWriter enthält Methoden zum synchronen (Write und WriteLine) oder asynchronen (WriteAsync und WriteLineAsync) Schreiben in eine Datei.StreamWriter contains methods to write to a file synchronously (Write and WriteLine) or asynchronously (WriteAsync and WriteLineAsync).
File stellt statische Methoden zum Schreiben von Text in eine Datei (z. B. WriteAllLines und WriteAllText) oder zum Anfügen von Text an eine Datei (z. B. AppendAllLines, AppendAllText und AppendText) bereit.File provides static methods to write text to a file, such as WriteAllLines and WriteAllText, or to append text to a file, such as AppendAllLines, AppendAllText, and AppendText.
Path wird für Zeichenfolgen verwendet, die Informationen zu Datei- oder Verzeichnispfaden enthalten.Path is for strings that have file or directory path information. Diese Klasse enthält die Combine-Methode und ab .NET Core 2.1 die Methoden Join und TryJoin, mit denen die Verkettung von Zeichenfolgen zum Erstellen eines Datei- oder Verzeichnispfads ermöglicht wird.It contains the Combine method and, in .NET Core 2.1 and later, the Join and TryJoin methods, which allow concatenation of strings to build a file or directory path.
Hinweis
In den folgenden Beispielen wird nur das Mindeste des erforderlichen Codes veranschaulicht.The following examples show only the minimum amount of code needed. Reale Anwendungen umfassen im Allgemeinen eine robustere Fehlerüberprüfung und Ausnahmebehandlung.A real-world app usually provides more robust error checking and exception handling.
Beispiel: Synchrones Schreiben von Text mit StreamWriterExample: Synchronously write text with StreamWriter
Im folgenden Beispiel wird gezeigt, wie Sie die StreamWriter-Klasse verwenden, um Text zeilenweise synchron in eine neue Datei zu schreiben.The following example shows how to use the StreamWriter class to synchronously write text to a new file one line at a time. Da das StreamWriter-Objekt in einer using
-Anweisung deklariert und instanziiert ist, wird die Dispose-Methode aufgerufen, die den Datenstrom automatisch leert und beendet.Because the StreamWriter object is declared and instantiated in a using
statement, the Dispose method is invoked, which automatically flushes and closes the stream.
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
Beispiel: Synchrones Anfügen von Text mit StreamWriterExample: Synchronously append text with StreamWriter
Im folgenden Beispiel wird gezeigt, wie Sie die StreamWriter-Klasse verwenden, um Text synchron an die Textdatei anzufügen, die im ersten Beispiel erstellt wurde.The following example shows how to use the StreamWriter class to synchronously append text to the text file created in the first example.
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
Beispiel: Asynchrones Schreiben von Text mit StreamWriterExample: Asynchronously write text with StreamWriter
Das folgende Beispiel zeigt, wie Sie Text mithilfe der StreamWriter -Klasse asynchron in eine neue Datei schreiben.The following example shows how to asynchronously write text to a new file using the StreamWriter class. Der Methodenaufruf muss sich innerhalb einer async
-Methode befinden, um die WriteAsync-Methode aufzurufen.To invoke the WriteAsync method, the method call must be within an async
method. Für das C#-Beispiel ist C# 7.1 oder höher erforderlich, da der Programmeinstiegspunkt den async
-Modifizierer unterstützt.The C# example requires C# 7.1 or later, which adds support for the async
modifier on the program entry point.
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.
Beispiel: Schreiben und Anfügen von Text mit der File-KlasseExample: Write and append text with the File class
Das folgende Beispiel zeigt, wie Sie mithilfe der File -Klasse Text in eine neue Datei schreiben und neue Textzeilen an diese Datei anfügen.The following example shows how to write text to a new file and append new lines of text to the same file using the File class. Durch die Methoden WriteAllText und AppendAllLines wird die Datei automatisch geöffnet und geschlossen.The WriteAllText and AppendAllLines methods open and close the file automatically. Wenn der für die WriteAllText -Methode angegebene Pfad bereits vorhanden ist, wird die Datei überschrieben.If the path you provide to the WriteAllText method already exists, the file is overwritten.
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
Siehe auchSee also
- StreamWriter
- Path
- File.CreateText
- Vorgehensweise: Auflisten von Verzeichnissen und DateienHow to: Enumerate directories and files
- Vorgehensweise: Lesen von bzw. Schreiben in eine neu erstellte DatendateiHow to: Read and write to a newly-created data file
- Vorgehensweise: Öffnen und Anfügen an eine ProtokolldateiHow to: Open and append to a log file
- Vorgehensweise: Lesen von Text aus einer DateiHow to: Read text from a file
- Datei- und Stream-E/AFile and stream I/O
Feedback
Feedback wird geladen...