gpt4 book ai didi

c# - SaveFileDialog问题(C#)(VS2008)

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:01 25 4
gpt4 key购买 nike

出于某种原因,我遇到了 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();
}
}
}

最佳答案

您在写入内容后还没有得到 tw.Close()。缓冲区不会被刷新。

关于c# - SaveFileDialog问题(C#)(VS2008),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2732917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com