[英]File creates but cannot write in it
我的程序:檢查Settings.txt文件。 如果文件不存在,請創建文本並自動寫入。 如果Settings.txt文件已存在,請忽略。 不要在現有文件中創建或寫入。
我的問題:當文件不存在時,Settings.txt文件會創建,但它是空的。 我希望程序在創建文件時寫入。 謝謝你的幫助。
private void Form1_Load(object sender, EventArgs e)
{
string path = @"C:\Users\Smith\Documents\Visual Studio 2010\Projects\Ver.2\Settings.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine("Manual Numbers=");
tw.WriteLine("");
tw.WriteLine("Installation Technical Manual: ");
tw.WriteLine("Performance Manual: ");
tw.WriteLine("Planned Maintenance Technical Manual: ");
tw.WriteLine("Service Calibration Manual: ");
tw.WriteLine("System Information Manual: ");
tw.WriteLine("");
tw.Close();
}
}
嘗試這個:
using(FileStream stream = File.Create(path))
{
TextWriter tw = new StreamWriter(stream);
tw.WriteLine("Manual Numbers=");
tw.WriteLine("");
tw.WriteLine("Installation Technical Manual: ");
tw.WriteLine("Performance Manual: ");
tw.WriteLine("Planned Maintenance Technical Manual: ");
tw.WriteLine("Service Calibration Manual: ");
tw.WriteLine("System Information Manual: ");
tw.WriteLine("");
}
即使在寫入過程中發生異常, 使用也可確保文件流被關閉(處理)。
問題是File.Create返回一個FileStream,因此它使文件保持打開狀態。 您需要將TextStream與TextWriter一起使用。 您還需要在using(...)語句中寫入FileStream,或者在FileStream上手動調用Dispose(),以確保在處理完文件后關閉該文件。
這就是我認為發生的事情。 當我復制並運行你的代碼時,拋出了一個異常。 這可能是因為您創建了兩次文件,並且在第二次創建文件之前不要關閉它。
作為參考, TextWriter tw = new StreamWriter(path);
為您創建文件。 您不需要調用File.Create
並且在后續運行期間,我認為你沒有刪除該文件,並且由於該文件已經存在, if (!File.Exists(path))
將永遠不會被滿足,並且將跳過整個if
語句
所以這里有多個要點
File.Create
調用 雖然我在很長一段時間后回答,但我想我應該回答
using (TextWriter tw = new StreamWriter(path))
{
StringBuilder sb = new StringBuilder();
sb.Append("Manual Numbers=");
sb.Append(Environment.NewLine);
sb.Append("Installation Technical Manual: ");
sb.Append("Performance Manual: ");
sb.Append("Planned Maintenance Technical Manual: ");
sb.Append("Service Calibration Manual: ");
sb.Append("System Information Manual: ");
sb.Append(Environment.NewLine);
tw.Write(sb.ToString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.