[英]C# Print to a text file from a windows form
我能夠獲得此代碼以在控制台應用程序中工作,但當前正在Windows窗體中工作。 我將輸出更改為控制台應用程序,但這仍然無法正常工作。
string path = @"C:\Users\rbc658\Trajectory.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter txt = new StreamWriter(path);
txt.WriteLine("Hello");
txt.Close();
}
else if (File.Exists(path))
{
using (var txt = new StreamWriter(path, true))
{
txt.WriteLine("Hello");
txt.Close();
}
}
“關閉”,“創建”和“寫行”未像上面的文本中突出顯示。 我正在使用system.io。 表單和控制台應用程序有什么不同之處會阻止其工作?
對於您來說,創建一個函數來向文本文件中寫入內容的調用更為優雅
下面的代碼為我工作:
private void Form1_Load(object sender, EventArgs e) // for example run this code when form loads
{
string path = @"C:\Users\Luka\Desktop\Trajectory.txt"; // your path to a text file
string text = "Hello"; // some text to write to a text file
Write(text, path, File.Exists(path)); // we are passing File.Exists(path) as a boolean to see wether or not to append text to a file
}
private void Write(string text, string path, bool file_exists)
{
//if File.Exists(path) is true, streamwriters second argument is true, so it appends
//else the argument is false and it does not append
StreamWriter txt = new StreamWriter(path, file_exists); // creates new object type StreamWriter with 2 arguments
//1. path to a file
//2. boolean to see wether or not to append the text to a file
txt.WriteLine(text); // writes text line to a file
txt.Dispose(); // disposes streamwriter
}
所有解釋都顯示為代碼中的注釋,因此您可以在測試程序時將其復制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.