简体   繁体   English

C#saveFileDialog打开两次

[英]C# saveFileDialog open twice

I have a datatable (dt) and a button to export the data to excel. 我有一个数据表(dt)和一个将数据导出到Excel的按钮。

I'm using ClosedXML to do the job done. 我正在使用ClosedXML来完成工作。

But, when I click on export button, I got first saveFileDialog and then after I click OK, I got a second saveFileDialog. 但是,当我单击导出按钮时,我得到了第一个saveFileDialog,然后单击确定之后,又得到了第二个saveFileDialog。 After this, the file is exported correctly. 此后,文件将正确导出。

So, the code... 所以,代码...

This is the main code for the button export action. 这是按钮导出操作的主要代码。 I'm using the saveFileDIalog to allow user choose the save file directory. 我正在使用saveFileDIalog允许用户选择保存文件目录。

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

Then, the methods 然后,方法

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

And the MemoryStream 还有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;
        }
    }

Can please someone help me see why I'm getting 2 saveFileDialog? 可以请人帮我看看为什么我得到2 saveFileDialog吗?

Thanks. 谢谢。

I see a problem; 我看到一个问题; I added some comments: 我添加了一些评论:

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

Edit: And other problems are reported in other users' comments (bad MemoryStream management) 编辑:其他用户的评论中报告了其他问题(坏的MemoryStream管理)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM