4

基本上,我想知道在以下下载文件问题时是否有最佳实践,不仅仅是临时使用,而是最终将它们移动到应用程序文件夹。我面临一些选择:

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

因为当时某些文件正在使用中,所以我无法选择将文件直接写入最终到达的位置。它必须去一个临时区域...

4

3 回答 3

8

您的第一个选择非常好。它非常清晰且有据可查。

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

于 2011-01-18T04:28:10.693 回答
1

//选项 4 - 临时应用程序路径 + 随机文件名

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

是最好的选择,因为它不会引发 SecurityExceptions 或 IOException 别人可以

于 2011-01-18T04:27:56.323 回答
0

这winforms?网络?WPF?什么?为什么不将其存储在应用程序用户的配置文件中?

于 2011-01-18T04:15:12.117 回答