[英]c# downloading file with WebClient and saving it
I have the code to download the file, It only replaces it. 我有下载文件的代码,它只会替换它。
WebClient webClient = new WebClient();
{
webClient.DownloadFile("http://test.png", "C:\PNG.png")
}
I only wonder, would it be possible to Download the file, then save the file instead of replacing the old file (in the example above, png.png). 我只想知道,是否可以下载文件,然后保存文件而不是替换旧文件(在上面的示例中为png.png)。
Create a unique name each time. 每次创建一个唯一的名称。
WebClient webClient = new WebClient();
{
webClient.DownloadFile("http://test.png", string.Format("C:\{0}.png", Guid.NewGuid().ToString()))
}
While Stephens answer is perfectly valid this may be unhandy sometimes. 尽管斯蒂芬斯的回答是完全正确的,但这有时可能是不方便的。 I'd suppose to create a temporary filename (which is not that different from what Stephen proposed, but in a temporary folder - most likely AppData/Local/Temp) and rename the file after the download is complete. 我想创建一个临时文件名(与Stephen提议的文件名没有什么不同,但是在一个临时文件夹中-最有可能是AppData / Local / Temp),并在下载完成后重命名该文件。 This class demonstrates the idea and I've not verified that it works as intended, but if it does feel free to use the very class. 此类演示了这个想法,但我尚未验证它是否可以按预期工作,但是可以随意使用该类。
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
}
}
If you'd like to display the progress you might expose an event, which is emitted when WebClient.DownloadProgressChanged
is thrown 如果要显示进度,则可以公开一个事件,该事件在抛出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.