我有下载文件的代码,它只替换它。
WebClient webClient = new WebClient();
{
webClient.DownloadFile("http://test.png", "C:\PNG.png")
}
我只是想知道,是否可以下载文件,然后保存文件而不是替换旧文件(在上面的例子中,png.png)。
答案 0 :(得分:3)
每次都创建一个唯一的名称。
WebClient webClient = new WebClient();
{
webClient.DownloadFile("http://test.png", string.Format("C:\{0}.png", Guid.NewGuid().ToString()))
}
答案 1 :(得分:1)
虽然斯蒂芬斯的回答是完全有效的,但有时这可能是不方便的。我想创建一个临时文件名(与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;
}
// ...
}