简体   繁体   中英

How to save file in a specific folder?

I need to save the .xlsx generate by epplus to the Desktop so I did:

 var dlg = new SaveFileDialog
        {
           FileName = "FileName" + DateTime.Now.ToString("dd-MM-yyyy"),
           DefaultExt = ".xlsx",
           Filter = "Excel Sheet (.xlsx)|*.xlsx", 
           RestoreDirectory = true,
           InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        };

and then:

using (FileStream fs = new FileStream(dlg.FileName, FileMode.Create))
{
       package.SaveAs(fs);
}

where package is the ExcelPackage package of epplus. This code should save the file to the desktop but I've two problems:

  • The file is saved into the bin directory of my application
  • The extension xlsx is missing when I specified that in the dlg definition

is that a bug or I'm doing something wrong?

Thanks for the attention.

Your code simply initialises the file dialog. You need to call "dlg.ShowDialog();" this will let you select a folder other than your initial folder. Ensure you click on the save button, if you click on cancel your initialised filename will not be modified with the path.

If you know you only want to save to the desktop you could use the Path.Combine method : https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx

String FilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFo‌​lder.Desktop),
    "FileName" + DateTime.Now.ToString("dd-MM-yyyy") + ".xlsx");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM