C#使用WebClient下載下傳檔案到本地目錄。
1、配置本地目錄路徑
<appSettings>
<!--檔案下載下傳目錄-->
<add key="Download_Dic" value="E:\MyDownloadFile\"/>
</appSettings>
2、建立FileHandler.cs類,編寫下載下傳代碼
/// <summary>
/// 檔案處理類
/// </summary>
public static class FileHandler
{
/// <summary>
/// 檔案下載下傳目錄
/// </summary>
private static string _directory = @ConfigurationSettings.AppSettings["Download_Dic"];
/// <summary>
/// 下載下傳檔案
/// </summary>
/// <param name="url">下載下傳位址</param>
/// <returns>檔案名稱</returns>
public static string DownloadFile(string url)
{
try
{
string fileName = CreateFileName(url);
if (!Directory.Exists(_directory))
{
Directory.CreateDirectory(_directory);
}
WebClient client = new WebClient();
client.DownloadFile(url, _directory + fileName);
return fileName;
}
catch
{
return "";
}
}
/// <summary>
/// 建立檔案名稱
/// </summary>
public static string CreateFileName(string url)
{
string fileName = "";
string fileExt = url.Substring(url.LastIndexOf(".")).Trim().ToLower();
Random rnd = new Random();
fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + rnd.Next(10, 99).ToString() + fileExt;
return fileName;
}
}
3、調用測試
static void Main(string[] args)
{
string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1494677827304&di=8e8aaf1a717ae37b73b772ee4728c7ea&imgtype=0&src=http%3A%2F%2Fscimg.jb51.net%2Fallimg%2F141123%2F10-1411231F92W16.jpg";
string fileName = FileHandler.DownloadFile(url);
if (!String.IsNullOrEmpty(fileName))
{
Console.WriteLine("檔案下載下傳成功,檔案名稱:" + fileName);
}
else
{
Console.WriteLine("檔案下載下傳失敗");
}
Console.ReadLine();
}