Search code examples
c#winformsepplussavefiledialog

Pass File Name and Location From SaveFileDialog To Variable


I have been just hard coding a save name/location, but now I need to ask the user for the save location and file name. I have this syntax, but how do I actually pass the selected location & input file name to my ToExcel() method to know the file name and save 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!");
    }
}

Solution

  • Firstly ShowDialog should be the last line of your call, after you have configured it

    then use the FileName Property to access the selected Filename

    finally pass that to whatever you need to pass it to 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){...}
    

    also if you want to get the Directorty of a FileInfo check the FileInfo.Directory property