【发布时间】:2012-01-16 18:20:56
【问题描述】:
我在保存当前打开的文件时遇到问题,但它没有弹出对话框询问将其保存在什么名称下。
为了让自己更清楚一点,我打开一个 .txt 文件并使用它,然后想单击“保存”并保存文件而不弹出“另存为”对话框。
这是我的存档代码:
private void SaveFile()
{
SaveFileDialog fileChooser = new SaveFileDialog();
fileChooser.Title = "Choose Save Location";
fileChooser.Filter = "Text Files (*.txt)|*.txt";
fileChooser.OverwritePrompt = false; //Removes warning
DialogResult result = fileChooser.ShowDialog();
if (result == DialogResult.Cancel)
{
return;
}
try
{
string fileName = fileChooser.FileName;
output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fileWriter = new StreamWriter(output);
foreach (Employee emp in employee)
{
fileWriter.WriteLine(emp.Firstname + "," + emp.Lastname + "," + emp.Position + "," + emp.Bmonth + "," + emp.Bday + "," + emp.BYear + "," + emp.Salary + "," + emp.Hiremonth + "," + emp.Hireday + "," + emp.Hireyear);
}
fileWriter.Close();
output.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
fileWriter.Close();
output.Close();
}
}
只要将其保存到 .txt 文件并重新加载,一切都很好,只是那个弹出窗口让我感到厌烦。
【问题讨论】:
-
如果您已经有了文件名,那么您完全跳过 fileChooser 对话框并保存它怎么样?我没有发现问题。
-
您在代码中专门显示了文件保存对话框。如果你不想那样...不要这样做。
-
如果我打开一个文件并对其进行更改,我只想能够单击工具栏上的“保存”并保存它,而不是询问以什么名称保存它。
-
然后将
fileName保存在一个变量中——就这么简单 -
@Andrew 如果我删除对话代码,我会收到“流不可写”错误。这可能是因为我之前没有关闭我的信息流吗?
标签: c# filestream save save-as