我正在尝试从本地网络设备下载多个文件: http file directory
我想编写一个代码,自动将所有这些.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 Unauthorized Error
问题2:能够使用WebProxy类进行身份验证但无法下载。获取403未找到错误。
代码:
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 Not Found
DOWNLOAD ERROR:System.Net.WebException:远程服务器返回错误:(404)Not Found。 在System.Net.WebClient.DownloadFile(Uri地址,字符串fileName) 在System.Net.WebClient.DownloadFile(String address,String fileName) 在C:\ Users \ Gordon \ documents \ visual studio 2015 \ Projects \ ConsoleApplication2 \ ConsoleApplication2 \ Program.cs:第139行中的ConsoleApplication2.Program.Main(String [] args)
请帮助我确定我的代码中是否有任何错误,或者是否有更好的方式提交凭据并下载所有文件。
提前致谢!
答案 0 :(得分:0)
我不是Dot Net开发者,我只是分享我的意见。 在第二点中,您提到您将获得403,这是Acces Denied的Http状态代码。我觉得你的凭证无效,或者你没有权利进行操作。