【问题标题】:How do I use a Save Dialog Box in C# to save an ASCII text file?如何在 C# 中使用保存对话框来保存 ASCII 文本文件?
【发布时间】:2009-12-29 21:25:44
【问题描述】:

好的,我可能在这里遗漏了一些非常简单的东西,但我已经在这个问题上做了一个多小时了,却一无所获。 :( 我有一个使用 Microsoft 的 Visual C# 2008 Express Edition 的 C# 项目。“保存”对话框根据需要显示,但它从不生成文件。实际上,一旦指定了文件,我希望应用程序以当前的方式维护它数据作为日志文件。现在,如果我能得到 ####### 的东西来制作一个空文件,我会很高兴。这是我到目前为止所能想到的:

      private void saveLogAsToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (DialogResult.OK == saveFileDialog1.ShowDialog())
         {
            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
/* This does not work.
               // Saves the Image via a FileStream created by the OpenFile method.
               System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();
               fs.Write((byte)"Success!\r\n", 0, 10);
               fs.Close();
*/
            }
            else
            {
               textBox1.Text += "An invalid filename was specified.\r\n";
            }

         }
      }

任何建议将不胜感激。谢谢。

【问题讨论】:

    标签: c# ascii text-files save-dialog


    【解决方案1】:

    Gabriel 的回答是正确的,只是他直接使用了 saveFileDialog1.FileName,而不是 SaveFileDialog 上的 OpenFile() 方法。如果您希望您的应用程序在部分信任环境中工作,那么您需要使用 OpenFile() 并直接访问 strread。

    请参阅this MSDN article 了解更多信息。

    这是等效的代码:

    using (var stream = dlg.OpenFile())
    using (var writer = new System.IO.StreamWriter(stream))
    {
        writer.WriteLine("Success");
    }
    

    【讨论】:

      【解决方案2】:

      这将起作用:

      using (System.IO.TextWriter tw = new System.IO.StreamWriter(saveFileDialog1.FileName))
      {
          tw.WriteLine("Success");
      }
      

      【讨论】:

        【解决方案3】:
        FileInfo fi = new FileInfo(saveFileDialog1.Filename); 
        StreamWriter stm = fi.OpenWrite;
        // or
        FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多