[英]C# Create txt file and save
我正在嘗試創建文件並保存文本,但是只有創建文件的人才能提出問題所在嗎?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.FileName = "Password";
sfd.Title = "Save Text File";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
StreamWriter bw = new StreamWriter(File.Create(path));
bw.Write(randomstring);
bw.Dispose();
}
}
您需要先調用bw.Close()
然后再調用bw.Dispose()
。 根據API:“您必須調用Close來確保將所有數據正確寫到基礎流中。” ( http://msdn.microsoft.com/zh-cn/library/system.io.streamwriter.close(v=vs.110).aspx )
我實際上將代碼更改為:
using (StreamWriter bw = new StreamWriter(File.Create(path)))
{
bw.Write(randomstring);
bw.Close();
}
無論是否成功完成, using
塊都會自動調用Dispose()
。
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//...
File.WriteAllText(path, randomstring);
}
bw.Write(randomstring);
bw.Dispose();
您編寫一些東西,然后完全處置該對象。 嘗試:
bw.Write(randomstring);
bw.Close();
bw.Dispose();
根據文檔 ,您需要在處理前調用bw.Close()
。 另外,您應該使用using
確保所有IDisposable
都得到正確處理。
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
using (var fs = File.Create(path))
using (StreamWriter bw = new StreamWriter(fs))
{
bw.Write(randomstring);
bw.Close();
}
}
或者只使用File.WriteAllText
:
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
File.WriteAllText(path, randomstring);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.