• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
半壁江山
博客园    首页    新随笔    联系   管理    订阅  订阅

生成并下载txt类型的文件

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

 

 

 

posted @ 2017-04-28 15:52  半壁江山  阅读(823)  评论(13)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3