【问题标题】:Trying to save file without using SaveFileDialog尝试在不使用 SaveFileDialog 的情况下保存文件
【发布时间】:2016-03-10 08:29:28
【问题描述】:

我正在创建一个文本编辑器,但我卡在 SaveFileDialog 窗口打开 并要求覆盖当前打开的文件。

我在 SO 上看到了所有类似的问题,但没有一个能够帮助我。我什至尝试过这个问题的代码:“Saving file without dialog”Saving file without dialog

我的程序遇到了 FileName 问题。

这是我目前的代码

namespace Text_Editor
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();

            open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            open.Title = "Open File";
            open.FileName = "";

            if (open.ShowDialog() == DialogResult.OK)
            {
                this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
                StreamReader reader = new StreamReader(open.FileName);
                richTextBox1.Text = reader.ReadToEnd();
                reader.Close();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();

            save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            save.Title = "Save File";

            save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            if (save.ShowDialog() == DialogResult.OK)
            {
                StreamWriter writer = new StreamWriter(save.FileName);
                writer.Write(richTextBox1.Text);
                writer.Close();
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saving = new SaveFileDialog();

            saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            saving.Title = "Save As";
            saving.FileName = "Untitled";

            if (saving.ShowDialog() == DialogResult.OK)
            {
                StreamWriter writing = new StreamWriter(saving.FileName);
                writing.Write(richTextBox1.Text);
                writing.Close();
            }
        }

    }
}

所以我的问题是如何修改我的代码,以便我可以保存当前打开的文件,而无需每次都打开 SaveFileDialog 框?

我明白这与我正在调用 .ShowDialog 的事实有关,但我不知道如何修改它。

【问题讨论】:

  • 那就别叫了……
  • 那么您希望用户在文本框中输入文件名还是什么?
  • 如果你知道文件的路径,就使用它,不要显示对话框。
  • 是的,我知道我不能调用它,但我不知道如何修改我的代码以免调用它。如果用户有一个打开的文本文件并且他们修改它,它应该只在点击保存时保存。不会打开询问必须保存在哪里的对话框。
  • Alex 我想我明白你在说什么。请你详细说明

标签: c# text-editor savefiledialog


【解决方案1】:

打开文件时,将FileName 保存在表单级变量或属性中。

现在在保存文件时,您可以使用此 FileName 而不是从 FileOpenDialog 获取它。

首先声明一个变量来保存表单级别的文件名

// declare at form level
private string FileName = string.Empty;

打开文件时,将文件名保存在这个变量中

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();

    open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
    open.Title = "Open File";
    open.FileName = "";

    if (open.ShowDialog() == DialogResult.OK)
    {
        // save the opened FileName in our variable
        this.FileName = open.FileName;
        this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
        StreamReader reader = new StreamReader(open.FileName);
        richTextBox1.Text = reader.ReadToEnd();
        reader.Close();
    }
}

并且在做SaveAs操作的时候,更新这个变量

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
    SaveFileDialog saving = new SaveFileDialog();

    saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

    saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
    saving.Title = "Save As";
    saving.FileName = "Untitled";

    if (saving.ShowDialog() == DialogResult.OK)
    {
        // save the new FileName in our variable
        this.FileName = saving.FileName;
        StreamWriter writing = new StreamWriter(saving.FileName);
        writing.Write(richTextBox1.Text);
        writing.Close();
    }
}

然后可以像这样修改保存功能:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(this.FileName))
    {
        // call SaveAs 
        saveAsToolStripMenuItem_Click(sender, e);
    } else {
        // we already have the filename. we overwrite that file.
        StreamWriter writer = new StreamWriter(this.FileName);
        writer.Write(richTextBox1.Text);
        writer.Close();
    }
}

在新建(和关闭)函数中,你应该清除这个变量

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
    // clear the FileName
    this.FileName = string.Empty;
    richTextBox1.Clear();
}

【讨论】:

    【解决方案2】:

    例如在你的类中创建一个新的字符串变量 字符串文件名 = string.empty

    然后

    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if(string.IsNullOrEmpty(filename)) {
     //Show Save filedialog
        SaveFileDialog save = new SaveFileDialog();
    
        save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
        save.Title = "Save File";
    
        save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    
        if (save.ShowDialog() == DialogResult.OK)
        {
            filename = save.FileName;
    
        }
       }
       StreamWriter writer = new StreamWriter(filename);
            writer.Write(richTextBox1.Text);
            writer.Close();
    }
    

    SaveFileDialog 现在仅在 fileName 为 null 或为空时打开

    【讨论】:

      【解决方案3】:

      您必须存储已保存文件的事实,例如通过将文件名存储在您拥有的Form 类的member variable 中。然后使用if 检查您是否已经保存了文件,然后使用ShowDialog() 显示SaveFileDialog(如果您没有)或不继续保存到已经定义的文件名(存储在您的成员变量中)。

      试一试,执行以下操作:

      • 定义一个string 成员变量,将其命名为_fileName(在你的类中为private string _fileName;
      • 在您的saveToolStripMenuItem_Click 方法中,检查它是否为null (if (null == _fileName))
      • 如果是null,像以前一样继续(显示对话框),获取文件名后,将其存储在您的成员变量中
      • 重构您的文件编写代码,以便您从文件对话框(如之前)或成员变量_fileName 中获取文件名

      玩得开心,C# 是一门很棒的编程语言。

      【讨论】:

        【解决方案4】:

        首先,saveAsToolStripMenuItem_Click 中提取方法:如果您想添加一个弹出菜单快速按钮,该怎么办?然后就执行

          public partial class Form1: Form {
            // File name to save text to  
            private String m_FileName = "";
        
            private Boolean SaveText(Boolean showDialog) {
              // If file name is not assigned or dialog explictly required
              if (String.IsNullOrEmpty(m_FileName) || showDialog) {
                // Wrap IDisposable into using
                using (SaveFileDialog dlg = new SaveFileDialog()) {
                  dlg.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
                  dlg.Title = "Save File";
                  dlg.FileName = m_FileName;  
        
                  if (dlg.ShowDialog() != DialogResult.OK) 
                    return false;
        
                  m_FileName = dlg.FileName;  
                } 
              }
        
              File.WriteAllText(m_FileName, richTextBox1.Text);
        
              this.Text = Path.GetFileNameWithoutExtension(m_FileName);
        
              return true;
            }
        
            private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
              // SaveAs: always show the dialog 
              SaveText(true);
            }
        
            private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
              // Save: show the dialog when required only
              SaveText(false);
            }
            ...
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-31
          • 1970-01-01
          • 1970-01-01
          • 2022-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多