簡體   English   中英

C#最佳實踐:編寫“臨時”文件以供下載:放在應用程序的環境文件夾或臨時文件夾中

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

基本上,我想知道下面的文件下載問題是否有最好的做法,不僅僅是臨時使用,而是最終將它們移動到應用程序文件夾。 我面臨一些選擇:

//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位。 正如Astander在這個答案中指出的那樣你可能想要使用AppDomain.BaseDirectory,因為對話框可以改變 Environment.CurrentDirectory

//選項4 - 臨時應用程序路徑+隨機文件名

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

是最好的選擇,因為它不會引發SecurityExceptions或其他人可以的IOException

這個勝利? 網? WPF? 什么? 為什么不將它存儲在應用程序用戶的配置文件中?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM