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

Pass File Name and Location From SaveFileDialog To Variable

我一直在硬编码保存 name/location,但现在我需要向用户询问保存位置和文件名。我有这种语法,但我如何将选定的位置和输入文件名实际传递给我的 ToExcel() 方法以了解文件名并保存位置?

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

首先ShowDialog应该是你调用的最后一行,在你配置之后

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

最终将它传递给任何你需要传递给 ie

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 的目录,请检查 FileInfo.Directory 属性