C# 最佳实践:编写“临时”文件以供下载:放置在应用程序的环境文件夹或临时文件夹中

2024-01-19

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

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

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


你的第一个选择非常好。这里发生的事情非常清楚且有据可查。

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

除了Environment.CurrentDirectory少量。正如阿斯坦德在《这个答案 https://stackoverflow.com/questions/2049126/openfiledialog-and-environment-currentdirectory/2049165#2049165您可能想使用 AppDomain.BaseDirectory 因为对话框可以改变 https://stackoverflow.com/questions/930816/why-does-openfiledialog-change-my-working-directory环境.当前目录

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 最佳实践:编写“临时”文件以供下载:放置在应用程序的环境文件夹或临时文件夹中 的相关文章

随机推荐