C#saveFileDialog打开两次

时间:2018-05-25 11:19:43

标签: c# memorystream savefiledialog

我有一个数据表(dt)和一个用于将数据导出到Excel的按钮。

我正在使用ClosedXML来完成工作。

但是,当我点击导出按钮时,我得到了第一个saveFileDialog,然后在我点击OK后,我得到了第二个saveFileDialog。在此之后,文件将正确导出。

所以,代码......

这是按钮导出操作的主要代码。我正在使用saveFileDIalog来允许用户选择保存文件目录。

private void exportarToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if(saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            FileInfo fileInfo = new FileInfo(saveFileDialog.FileName);
            SaveToExcel(dt, fileInfo);
        }
    }

然后,方法

public static void SaveToExcel(System.Data.DataTable dt, FileInfo outputFile)
    {
        XLWorkbook wb = new XLWorkbook();
        var worksheet = wb.Worksheets.Add(dt, "ResultTable");

        using (MemoryStream memoryStream = GetStream(wb))
        {
            File.WriteAllBytes(outputFile.FullName, memoryStream.ToArray());
        }
    }

和MemoryStream

public static MemoryStream GetStream(XLWorkbook excelWorkbook)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            excelWorkbook.SaveAs(stream, new SaveOptions { EvaluateFormulasBeforeSaving = false, GenerateCalculationChain = false, ValidatePackage = false,  });
            return stream;
        }
    }

请有人帮我看看为什么我得到2个saveFileDialog?

感谢。

1 个答案:

答案 0 :(得分:0)

我看到了一个问题;我添加了一些评论:

private void exportarToolStripMenuItem_Click(object sender, EventArgs e)
{
    string filename = saveFileDialog.FileName; // what is this for? I would remove it.
    if(saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        // problem in the following line, explained below
        string path = Path.GetFullPath(filename);
        // you should be picking the saveFileDialog.FileName at this point  to get
        // the user selection, not the filename variable you got before;
        // moreover, the saveFileDialog.FileName is already a full path, no need to
        // call the Path.GetFullPath method
        FileInfo fileInfo = new FileInfo(path);
        SaveToExcel(dt, fileInfo);
    }
}

编辑:其他用户报告了其他问题'评论(糟糕的MemoryStream管理)