我遇到了保存当前打开的文件的问题,而没有弹出对话框询问保存它的名称。
为了更清楚地说明一下,我打开一个.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文件并重新加载,一切都很有效,只是那个让我烦恼的弹出窗口。
答案 0 :(得分:2)
fileChooser
对象是SaveFileDialog
对象。你通过调用它来显示它:
DialogResult result = fileChooser.ShowDialog();
如果您不想显示对话框,只需省略fileChooser
代码,然后使用:
string fileName = strAlreadyKnownFileName;
答案 1 :(得分:0)
我首先在一些变量中保存已打开文件的完整路径,然后说:
private string filepath = "path/to/my/file";
然后你需要创建一个按钮并调用它,即“保存”双击按钮并编写这个简单的代码,以保存你想要的当前打开的文件:
就这么简单......
编辑:
private void SaveFile()
{
//do your loop and stuff in here and finally write your text to the file using this
File.WriteAllText(filepath, yourtexttobesaved);
}