Nasıl olur: Dosyaya metin yazma
Bu konu, bir .NET uygulaması için dosyaya metin yazmanın farklı yollarını gösterir.
Aşağıdaki sınıflar ve yöntemler genellikle bir dosyaya metin yazmak için kullanılır:
StreamWriter , bir dosyaya zaman uyumlu ( ve ) veya zaman uyumsuz olarak ( ve ) yazma Write WriteLine yöntemlerini WriteAsync WriteLineAsync içerir.
File , ve gibi bir dosyaya metin yazmak veya , ve gibi bir dosyaya metin eklemek WriteAllLines WriteAllText için statik yöntemler AppendAllLines AppendAllText AppendText sağlar.
Path , dosya veya dizin yolu bilgilerine sahip dizeler için kullanılır. Combine.NET Core 2.1 ve sonraki bir zaman için ve yöntemlerini içerir. Bu yöntem, dizelerin bir dosya veya dizin yolu oluşturmasına Join olanak TryJoin sağlar.
Not
Aşağıdaki örneklerde yalnızca gereken en düşük kod miktarı verilmiştir. Gerçek dünya uygulaması genellikle daha güçlü hata denetimi ve özel durum işleme sağlar.
Örnek: StreamWriter ile zaman uyumlu olarak metin yazma
Aşağıdaki örnek, yeni bir dosyaya aynı anda bir satıra zaman uyumlu olarak metin StreamWriter yazmak için sınıfının nasıl kullanılacagını gösterir. Nesne bir deyimde bildirilir ve örneklenir, otomatik olarak boşaltan ve akışı kapatan StreamWriter using yöntemi Dispose çağrılır.
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
Ingilizce dışındaki dillere çevrilmiş kod açıklamalarını görmek isterseniz, Bu GitHub tartışma sorununubize tanıyın.
Örnek: StreamWriter ile metni zaman uyumlu olarak ekleme
Aşağıdaki örnek, ilk örnekte oluşturulan metin dosyasına zaman uyumlu olarak metin eklemek StreamWriter için sınıfının nasıl kullanılası gösterir.
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
Örnek: StreamWriter ile zaman uyumsuz metin yazma
Aşağıdaki örnek, sınıfını kullanarak metinleri zaman uyumsuz olarak yeni bir dosyaya nasıl yazacaklarını StreamWriter gösterir. yöntemini çağırmak WriteAsync için yöntem çağrısının bir yöntemin içinde olması async gerekir. C# örneği için C# 7.1 veya sonrası gerekir ve bu da program giriş noktasında değiştirici async desteği ekler.
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.
Örnek: Dosya sınıfıyla metin yazma ve ekleme
Aşağıdaki örnek, sınıfını kullanarak yeni bir dosyaya metin yazmayı ve aynı dosyaya yeni metin satırları eklemeyi File gösterir. ve WriteAllText yöntemleri dosyayı otomatik olarak açıp AppendAllLines kapatır. Yöntemine sağ istediğiniz yol WriteAllText zaten varsa dosyanın üzerine yazılır.
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