webclient 根据链接地址登陆后获取文件

public static string DownloadFile(string strSourceUrl, string strDestFolder, string strUserName, string strPassword, string strDomain)
{
try
{
WebClient webclient = CreateWebClient(strUserName, strPassword, strDomain);

// 下载
Byte[] filecontents = webclient.DownloadData(strSourceUrl);

string strFileName = Path.GetFileName(strSourceUrl);

// 创建文件
FileStream fs = new FileStream(strDestFolder + strFileName, FileMode.Create, FileAccess.Write);
// 写文件
fs.Write(filecontents, 0, filecontents.Length);

fs.Close();
return strFileName;
}
catch (Exception ex)
{

}

return null;
}

// 创建WebClient
// 参数:用户名,密码,域(用来登陆SharePoint)
private static WebClient CreateWebClient(string strUserName, string strPassword, string strDomain)
{
WebClient webclient = new WebClient();

if (String.IsNullOrEmpty(strUserName))
{
webclient.UseDefaultCredentials = true;
}
else
{
NetworkCredential credential = new NetworkCredential(strUserName, strPassword, strDomain);
webclient.Credentials = credential;
}
return webclient;
}

为记录,方便查阅

原文地址:https://www.cnblogs.com/liubinurl/p/4971133.html