-1

我在保存当前打开的文件时遇到问题,但没有弹出对话框询问将其保存在什么名称下。

为了更清楚地说明自己,我打开一个 .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 文件并将其重新加载,只是那个弹出窗口让我感到厌烦。

4

2 回答 2

2

fileChooser对象是SaveFileDialog对象。您通过调用以下命令使其显示:

DialogResult result = fileChooser.ShowDialog();

如果您不想显示对话框,只需省略fileChooser代码,而是使用:

string fileName = strAlreadyKnownFileName;
于 2012-01-16T18:34:49.863 回答
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);
}
于 2012-01-16T18:41:31.523 回答