出于某种原因,我遇到了SaveFileDialog的问题。我想要做的就是逐行从文本框中提取数据并将其写入文本文件,然后将该文本文件保存到桌面。第一段代码工作正常(虽然它不保存到桌面)。代码的第二位是我想要使用的,但是当它创建文本文件时,文本文件是空的。我在第二段代码中做错了什么?
此代码有效,但它不会保存到桌面,并且不如第二个代码那么好。
//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();
}
}
}
答案 0 :(得分:4)
写完内容后,您还没有tw.Close()
。缓冲区不会被刷新。
答案 1 :(得分:3)
正如ChrisT所说,你永远不会关闭StreamWriter。但是,作为最佳实践,您应该有using
块来关闭/处理这些块。
//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();
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)
{
using (Stream savestream = saveFialog.OpenFile())
{
if (saveStream != null)
{
using(StreamWriter tw = new StreamWriter(saveStream))
{
for (int i = 0; i < textBoxLines; i++)
{
tw.WriteLine(textBox.Lines.GetValue(i));
}
}
}
}
}
}