首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获奖表格: SaveFileDialog

获奖表格: SaveFileDialog
EN

Stack Overflow用户
提问于 2012-02-20 19:19:40
回答 3查看 11.1K关注 0票数 2

我在保存按钮中添加了以下代码:

代码语言:javascript
复制
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{                
    FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
    StreamWriter writer = new StreamWriter(fs);
    writer.Write(twexit.Text);       // twexit is previously created  
    writer.Close();
    fs.Close();
}

当我键入文件名并单击保存时,系统显示该文件不存在。我知道它不存在,但我设置了FileMode.Create。那么,如果文件不存在,它不应该创建文件吗?

EN

回答 3

Stack Overflow用户

发布于 2012-02-20 19:22:05

SaveFileDialog中有一个选项CheckFileExists,如果选定的文件不存在,该选项会使对话框显示该消息。您应该将此设置保留为false (这是默认值)。

票数 4
EN

Stack Overflow用户

发布于 2013-07-02 22:20:04

您可以简单地使用以下命令:

代码语言:javascript
复制
File.WriteAllText(saveFileDialog1.FileName, twexit.Text);

而不是使用流编写大量代码。它会创建新文件或覆盖它。File是System.Io的类。如果您想知道文件是否存在,请使用

代码语言:javascript
复制
File.Exist(filePath)

再见

票数 1
EN

Stack Overflow用户

发布于 2012-02-20 19:28:26

像这样使用:

代码语言:javascript
复制
     SaveFileDialog dlg = new SaveFileDialog();

        dlg.Filter = "csv files (*.csv)|*.csv";
        dlg.Title = "Export in CSV format";

        //decide whether we need to check file exists
        //dlg.CheckFileExists = true;

        //this is the default behaviour
        dlg.CheckPathExists = true;

        //If InitialDirectory is not specified, the default path is My Documents
        //dlg.InitialDirectory = Application.StartupPath;

        dlg.ShowDialog();
        // If the file name is not an empty string open it for saving.
        if (dlg.FileName != "")

        //alternative if you prefer this
        //if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK
            //&& dlg.FileName.Length > 0)

        {
            StreamWriter streamWriter = new StreamWriter(dlg.FileName);
            streamWriter.Write("My CSV file\r\n");
            streamWriter.Write(DateTime.Now.ToString());
            //Note streamWriter.NewLine is same as "\r\n"
            streamWriter.Write(streamWriter.NewLine);
            streamWriter.Write("\r\n");
            streamWriter.Write("Column1, Column2\r\n");
            //…
            streamWriter.Close();
        }

        //if no longer needed
        //dlg.Dispose();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9360270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档