问题
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...
回答1:
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
回答2:
//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
回答3:
This winforms? Web? WPF? what? Why not just store it in the application user's profile?
来源:https://stackoverflow.com/questions/4720417/c-sharp-best-practices-writing-temporary-files-for-download-place-in-applica