[英]c# downloading file with WebClient and saving it
我有下載文件的代碼,它只會替換它。
WebClient webClient = new WebClient();
{
webClient.DownloadFile("http://test.png", "C:\PNG.png")
}
我只想知道,是否可以下載文件,然后保存文件而不是替換舊文件(在上面的示例中為png.png)。
每次創建一個唯一的名稱。
WebClient webClient = new WebClient();
{
webClient.DownloadFile("http://test.png", string.Format("C:\{0}.png", Guid.NewGuid().ToString()))
}
盡管斯蒂芬斯的回答是完全正確的,但這有時可能是不方便的。 我想創建一個臨時文件名(與Stephen提議的文件名沒有什么不同,但是在一個臨時文件夾中-最有可能是AppData / Local / Temp),並在下載完成后重命名該文件。 此類演示了這個想法,但我尚未驗證它是否可以按預期工作,但是可以隨意使用該類。
class CopyDownloader
{
public string RemoteFileUrl { get; set; }
public string LocalFileName { get; set; }
WebClient webClient = new WebClient();
public CopyDownloader()
{
webClient.DownloadFileCompleted += WebClientOnDownloadFileCompleted;
}
public void StartDownload()
{
var tempFileName = Path.GetTempFileName();
webClient.DownloadFile(RemoteFileUrl, tempFileName, tempFileName)
}
private void WebClientOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
{
string tempFileName = asyncCompletedEventArgs.UserState as string;
File.Copy(tempFileName, GetUniqueFileName());
}
private string GetUniqueFilename()
{
// Create an unused filename based on your original local filename or the remote filename
}
}
如果要顯示進度,則可以公開一個事件,該事件在拋出WebClient.DownloadProgressChanged
時發出
class CopyDownloader
{
public event DownloadProgressChangedEventHandler ProgressChanged;
private void WebClientOnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs downloadProgressChangedEventArgs)
{
if(ProgressChanged != null)
{
ProgressChanged(this, downloadProgressChangedEventArgs);
}
}
public CopyDownloader()
{
webClient.DownloadFileCompleted += WebClientOnDownloadFileCompleted;
webClient.DownloadProgressChanged += WebClientOnDownloadProgressChanged;
}
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.