Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 834
michael Avatar asked Jan 20 '23 17:01

michael


2 Answers

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

like image 144
Conrad Frix Avatar answered Jan 30 '23 13:01

Conrad Frix


//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

like image 36
Artur Mustafin Avatar answered Jan 30 '23 13:01

Artur Mustafin