将文件名和位置从SaveFileDialog传递到变量

时间:2017-08-15 13:52:22

标签: c# winforms epplus savefiledialog

我刚刚编写了一个保存名称/位置的硬编码,但现在我需要询问用户保存位置和文件名。我有这个语法,但我如何实际传递选定的位置&输入文件名到我的ToExcel()方法以了解文件名并保存locaiton?

private void btnSave_Click(object sender, EventArgs e)
{
    //Creating Save File Dialog
    SaveFileDialog save = new SaveFileDialog();
    //Showing the dialog
    save.ShowDialog();
    //Setting default directory
    save.InitialDirectory = @"C:\";
    save.RestoreDirectory = true;
    //Setting title
    save.Title = "Select save location and input file name";
    //filtering to only show .xml files in the directory
    save.DefaultExt = "xml";
    //Write Data To Excel
    ToExcel();
}

private void ToExcel()
{
    var file = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Test_" + DateTime.Now.ToString("M-dd-yyyy-HH.mm.ss") + ".xlsx"));

    using (var package = new ExcelPackage(file))
    {
        ExcelWorksheet ws = package.Workbook.Worksheets.Add("Test");
        ws.Cells[1, 1].Value = "One";
        ws.Cells["A1:C1"].Style.Font.Bold = true;
        package.Save();
        MessageBox.Show("Saved!");
    }
}

1 个答案:

答案 0 :(得分:2)

首先ShowDialog应该是您配置后的最后一行电话

然后使用FileName属性访问所选的文件名

最后将它传递给你需要传递给它的任何东西,即

private void btnSave_Click(object sender, EventArgs e)
{
    SaveFileDialog save = new SaveFileDialog();
    save.InitialDirectory = @"C:\";
    save.RestoreDirectory = true;
    save.Title = "Select save location file name";
    save.DefaultExt = "xml"; // surely should be xlsx??

    //Showing the dialog
    if(save.ShowDialog() == DialogResult.OK)
    {
        ToExcel(save.FileName);
    }
}
private void ToExcel(string saveFile){...}

如果您想获取FileInfo的Directorty,请检查FileInfo.Directory属性