public ActionResult Index()
{
return View();
}
/// <summary>
/// 獲取網頁源碼,並將其寫入txt文件中,下載到本地
/// </summary>
/// <param name="webUrl">輸入的網址,如:http://www.17k.com/ </param>
/// <returns></returns>
public FileResult DownloadWebSource(string webUrl)
{
if (string.IsNullOrEmpty(webUrl.Trim()))
{
return null;
}
WebClient wc = new WebClient();
Stream st = wc.OpenRead(webUrl);//打開並讀取網頁數據
StreamReader sr = new StreamReader(st, System.Text.Encoding.UTF8);//以流的形式讀取數據
string strContent = sr.ReadToEnd();//讀取流數據,最終轉換成字符串形式
string filePath = "/DownLoad/TXT";
string fileMapPath = Server.MapPath(filePath);//獲取該文件夾的虛擬路徑相對應的物理路徑
//判斷該文件夾是否存在,若不存在,就創建新文件夾
if (!Directory.Exists(fileMapPath))
{
Directory.CreateDirectory(fileMapPath);
}
string txtPath = filePath + "/" + Guid.NewGuid().ToString().Replace("-", "").ToUpper() + ".txt";
string txtMapPath = Server.MapPath(txtPath);//獲取該文件的虛擬路徑相對應的物理路徑
//文件存在就打開,不存在就創建
FileStream fs = new FileStream(txtMapPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs.Dispose();//釋放資源
StreamWriter sw = new StreamWriter(txtMapPath, true);//為指定的文件初始化一個新的實例
sw.Write(strContent);//將獲取到的數據寫入到該文件中
sw.Close();//關閉當前流
return File(txtMapPath, "application/ms-txt", "網頁源代碼.txt");
}
#endregion