zoukankan      html  css  js  c++  java
  • 生成并下载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

  • 相关阅读:
    Jdbc增删改查的相关操作(Oracle 数据库环境)
    java
    今日随笔
    爬虫之链家网
    爬虫之搜狗
    【题解】「UVA1149」装箱 Bin Packing
    【题解】「SP34013」SEUG
    【题解】「SP867」 CUBES
    【题解】NOI 系列题解总集
    APIO2019简要题解
  • 原文地址:https://www.cnblogs.com/xuanhai/p/6781946.html
Copyright © 2011-2022 走看看