在asp.net中 把一个文本文档的中的数据一行一行添加到textbox中

先把文本文档上传到服务器上用viewstate保存路径

  /// <summary>
    /// 上传文件
    /// </summary>
    /// <returns></returns>
    public bool StartPostFile()
    {
        bool mark = true;

        string fileName = this.fuText.FileName;
        string fileType = fileName.Substring(fileName.LastIndexOf('.'));

        if (fileType == ".txt" && fuText.PostedFile.ContentLength <= 2097152)
        {

            string tempFileName = Guid.NewGuid().ToString();

            string tempFilePath = Server.MapPath("TempFiles/") + tempFileName + ".txt";
            ViewState["tempFileP"] = tempFilePath;
            this.fuText.PostedFile.SaveAs(tempFilePath);
        }
        else
        {
            mark = false;
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "zz", "alert('文件导入失败,请确保文件为excel文件,并且文件不大于2MB')", true);
        }

        return mark;
    }

 

 

然后读取文本中内容,一行一行读取数据(有要求必须是一行一行的)

 /// <summary>
    /// 文本的导入
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnText_Click(object sender, EventArgs e)
    {
        if (StartPostFile())
        {
            int result = 0;//显示添加的行数
            string path = ViewState["tempFileP"].ToString();
            StreamReader srReadLine = new StreamReader((System.IO.Stream)File.OpenRead(path),System.Text.Encoding.ASCII);
            srReadLine.BaseStream.Seek(0, SeekOrigin.Begin);
            while (srReadLine.Peek() > -1)
            {
                result++;
                this.txtNames.Text += srReadLine.ReadLine() + "/n";               
            }          
            srReadLine.Close();
            int count = Convert.ToInt32(this.lblCount.Text);
            this.lblCount.Text = count + result+"";//总共的行数
        }
    }

 

你可能感兴趣的:(asp.net)