【问题标题】:Saving a currently opened file without prompts在没有提示的情况下保存当前打开的文件
【发布时间】: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


【解决方案1】:

fileChooser 对象是 SaveFileDialog 对象。您正在通过调用使其显示:

DialogResult result = fileChooser.ShowDialog();

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

string fileName = strAlreadyKnownFileName;

【讨论】:

    【解决方案2】:

    我首先将打开文件的完整路径保存在某个变量中,比如说:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-12
      • 2012-12-11
      • 2017-07-18
      • 1970-01-01
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 2015-11-07
      相关资源
      最近更新 更多