由於某種原因,我遇到了SaveFileDialog問題。我想要做的就是從文本框中逐行提取數據並將其寫入文本文件,然後將該文本文件保存到桌面。第一部分代碼工作正常(儘管它不保存到桌面)。代碼的第二位是我想要使用的,但是當它創建文本文件時,文本文件是空的。我在第二部分代碼中做了什麼錯誤?SaveFileDialog問題(C#)(VS2008)
此代碼有效,但不會保存到桌面,並且不如第二個代碼。
//When the Save button is clicked the contents of the text box will be written to a text file.
private void saveButton_Click(object sender, EventArgs e)
{
int textBoxLines = textBox.Lines.Count();
if (File.Exists(saveFile))
{
result = MessageBox.Show("The file " + saveFile + " already exists.\r\nDo you want to replace it?", "File Already Exists!", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
TextWriter tw1 = new StreamWriter(saveFile);
for (int i = 0; i < textBoxLines; i++)
{
tw1.WriteLine(textBox.Lines.GetValue(i));
}
tw1.Close();
}
if (result == DialogResult.No)
{
MessageBox.Show("Please move or rename existing " + saveFile + "\r\nBefore attempting to save again.", "Message");
}
}
else
{
TextWriter tw2 = new StreamWriter(saveFile);
for (int i = 0; i < textBoxLines; i++)
{
tw2.WriteLine(textBox.Lines.GetValue(i));
}
tw2.Close();
}
}
此代碼不能正常工作,但我想用什麼。
//When the Save button is clicked the contents of the text box will be written to a text file.
private void saveButton_Click(object sender, EventArgs e)
{
int textBoxLines = textBox.Lines.Count();
Stream saveStream;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
saveDialog.RestoreDirectory = true;
saveDialog.FileName = (saveFile);
saveDialog.InitialDirectory = (Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
if (saveDialog.ShowDialog() == DialogResult.OK)
{
if ((saveStream = saveDialog.OpenFile()) != null)
{
StreamWriter tw = new StreamWriter(saveStream);
for (int i = 0; i < textBoxLines; i++)
{
tw.WriteLine(textBox.Lines.GetValue(i));
}
saveStream.Close();
}
}
}
謝謝你,現在很好。我在這裏使用的代碼: http://zamov.online.fr/EXHTML/CSharp/CSharp_302155.html 它沒有StreamWriter.Close(),我認爲只是關閉流就足夠了。我還注意到,當我第一次將我的tw.Close()放到第一次崩潰時,因爲在關閉流之後關閉了它,但是當我在saveStream.Close()之前放置tw.Close()時,一切正常。它爲什麼第一次崩潰? – ubiquibacon 2010-04-28 20:42:09
@typoknig - 當它墜毀時,你會得到什麼錯誤? – ChrisF 2010-04-28 20:43:45
'使用'塊會在這裏節省很多麻煩。 – Powerlord 2010-04-28 20:48:44