简体   繁体   中英

C# Best Practices: Writing “temporary” files for download: Place in applicaion's environment folder or temp folder

Basically, I'm wondering if there is a best practice when it comes to the following issue of downloading files, not just for temporary use, but eventually to move them to the application folder. I'm faced with some options:

//Option 1 - Random file
String tempfile = Path.GetTempFileName();
WriteData(tempfile);
File.Move(tempfile, Path.Combine(Environment.CurrentDirectory, filename);

//Option 2 - Temp Path + Random file name
String tempfile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
WriteData(tempfile);
File.Move(tempfile, Path.Combine(Environment.CurrentDirectory, filename);

//Option 3 - Temp Path + real file name
String tempfile = Path.Combine(Path.GetTempPath(), filename);
WriteData(tempfile);
File.Move(tempfile, Path.Combine(Environment.CurrentDirectory, filename);

//Option 4 - Temp Application Path + Random file name
String tempfile = Path.Combine(Environment.CurrentDirectory, Settings.Default.DownloadFolder, Path.GetRandomFileName());
WriteData(tempfile);
File.Move(tempfile, Path.Combine(Environment.CurrentDirectory, filename);

//Optioin 5 - Temp Application Path + file name
String tempfile = Path.Combine(Environment.CurrentDirectory, Settings.Default.DownloadFolder, filename);
WriteData(tempfile);
File.Move(tempfile, Path.Combine(Environment.CurrentDirectory, filename);

Because some files are in use at the time I don't have the option of writing the file directly to where it ends up going. It has to go to a temporary area...

Your first option is very nice. Its pretty clear and well documented whats going on here.

//Option 1 - Random file
String tempfile = Path.GetTempFileName();
WriteData(tempfile);
File.Move(tempfile, Path.Combine(Environment.CurrentDirectory, filename);

Except for the Environment.CurrentDirectory bit. As Astander points out in this answer you probably want to use AppDomain.BaseDirectory because the dialogs can change the Environment.CurrentDirectory

//Option 4 - Temp Application Path + Random file name

String tempfile = Path.Combine(Environment.CurrentDirectory, Settings.Default.DownloadFolder, Path.GetRandomFileName());
WriteData(tempfile);
File.Move(tempfile, Path.Combine(Environment.CurrentDirectory, filename);

Is the best choice, because it would not raise SecurityExceptions or IOException others can

This winforms? Web? WPF? what? Why not just store it in the application user's profile?

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