我在通过C#下载文件时遇到问题。
我有一个可以像这样处理下载的类:
namespace Ultra_Script
{
class FileDownloader
{
private readonly string _url;
private readonly string _fullPathWheretoSave;
private bool _result = false;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);
public FileDownloader(string url, string fullPathWheretoSave)
{
if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
if (string.IsNullOrEmpty(fullPathWheretoSave)) throw new ArgumentNullException("fullPathWhereToSave");
this._url = url;
this._fullPathWheretoSave = fullPathWheretoSave;
}
public bool StartDownload(int timeout)
{
try
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWheretoSave));
if (File.Exists(_fullPathWheretoSave))
{
File.Delete(_fullPathWheretoSave);
}
using (WebClient client = new WebClient())
{
var ur = new Uri(_url);
//client.Credentials = new NetworkCredential("username", "password");
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadFileCompleted += WebClientDownloadCompleted;
Console.WriteLine(@"Downloading File:");
client.DownloadFileAsync(ur, _fullPathWheretoSave);
_semaphore.Wait(timeout);
return _result && File.Exists(_fullPathWheretoSave);
}
}
catch (Exception e)
{
Console.WriteLine("Cant download file");
Console.Write(e);
return false;
}
finally
{
this._semaphore.Dispose();
}
}
private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.Write("/r --> {0}%", e.ProgressPercentage);
}
private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
{
_result = !args.Cancelled;
if (!_result)
{
Console.Write(args.Error.ToString());
}
Console.WriteLine(Environment.NewLine + "Download Finished!");
_semaphore.Release();
}
public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
{
return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
}
}
}
我这样称呼它:
public static void InstallBasicSW()
{
var succes = FileDownloader.DownloadFile("https://github.com/Corbieman/Basic_SW/raw/master/JaVa.exe", "C:\\Windows", 99999999);
Console.WriteLine("Done - Succes: " + succes);
Console.ReadLine();
}
但是只有在控制台中输入的内容是
下载完成!
完成-成功:错误;
我没有收到任何错误消息或进度条。这则消息会立即弹出。文件不会下载到该路径。任何人都知道或知道哪里可能出问题了?
答案 0 :(得分:1)
DownloadFile方法的参数需要完整文件的路径。
尝试一下:
public static void InstallBasicSW()
{
var succes = FileDownloader.DownloadFile("https://github.com/Corbieman/Basic_SW/raw/master/JaVa.exe", @"C:\Temps\JaVa.exe", 99999999);
Console.WriteLine("Done - Succes: " + succes);
Console.ReadLine();
}
为什么会有这个结果? 我认为这是因为您传递的是目录路径而不是文件路径。 下载会取消并立即完成。
明确的例外会更有帮助...
答案 1 :(得分:0)
所以问题是我不得不以管理员身份运行它,并像您所说的那样更正路径。现在可以正常工作了,谢谢。