[英]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.