将文件名和位置从"保存文件"对话框传递到变量



我一直在硬编码保存名称/位置,但现在我需要向用户询问保存位置和文件名。 我有这个语法,但是我如何将选定的位置和输入文件名实际传递给我的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!");
}
}

首先,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的Directorty,请检查FileInfo.Directory属性

最新更新