2017-08-15 63 views
-1

我一直在编写保存名称/位置的硬编码,但现在我需要询问用户保存位置和文件名。我有这样的语法,但我怎么实际上通过选择的位置&输入文件名到我的ToExcel()方法知道文件名并保存位置?从SaveFileDialog传递文件名和位置到变量

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

您应该使用OpenFileDialog来选择现有文件,Save用于创建不存在的文件,FolderBrowserDialog用于选择文件夹 – MikeT

+1

也可以说'//过滤只显示目录中的.xml文件这不是正确的过滤你将使用此代码'openFileDialog1.Filter =“txt文件(* .txt)| * .txt |所有文件(*。*)| *。*”;'DefaultExt用于确定使用什么扩展名if没有指定 – MikeT

回答

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财产

+0

Aww男子,我用FileName和FileNames做了它,并且你击败了我。 – Aaron

+0

我得到'DialogResult'的编译错误不包含'Ok'的定义 – BellHopByDayAmetuerCoderByNigh

+0

@BellHopByDayAmetuerCoderByNigh尝试“save.ShowDialog()== true” - 我相信这是一个c#4.0的东西。仍然是一个很好的回答,他只需要将它更新为C#4.0。 – Aaron