我正在尝试从本地网络设备下载几个文件: http 文件目录
我想编写一个代码,将所有这些 .avi 文件自动下载到我的电脑驱动器。
我有两个问题:
问题 1:仅使用 WebClient 类进行身份验证。如果我只使用 WebClient 类进行连接,则会收到 401 Unauthorized 错误。
代码:
try
{
using (WebClient myWebClient = new WebClient())
{
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = new NetworkCredential("user", "pword");
String userName = "user";
String passWord = "pword";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
myWebClient.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
Console.WriteLine("Header AUTHORIZATION: "+ myWebClient.Headers[HttpRequestHeader.Authorization].ToString());
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
错误消息:无法验证 401 未经授权的错误
问题 2:能够使用 WebProxy 类进行身份验证,但无法下载。出现 403 Not found 错误。
代码:
try
{
using (WebClient myWebClient = new WebClient())
{
WebProxy wp = new WebProxy("http://192.168.2.72:81/sd/20170121/record000/",false);
wp.Credentials = new NetworkCredential("user","pword");
Console.WriteLine("Web Proxy: " + wp.Address);
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = wp.Credentials;
myWebClient.Proxy = wp;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\"\n\n", filename, wp.Address);
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
错误消息:403 未找到
下载错误:System.Net.WebException:远程服务器返回错误:(404)未找到。在 System.Net.WebClient.DownloadFile(Uri address, String fileName) 在 System.Net.WebClient.DownloadFile(String address, String fileName) 在 ConsoleApplication2.Program.Main(String[] args) 在 C:\Users\Gordon\文档\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 139
请帮助我确定我的代码中是否有任何错误,或者是否有更好的方法来提交凭据并下载所有文件。
提前致谢!