读取.csv文件数据

using System.IO;

 

private void UploadFile()
    {
        try
        {
            if (!FileUpload1.HasFile)
            {
                Response.Write("文件不存在");
                return;
            }

            string fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();//获得文件后缀

            if (!fileExtension.Equals(".csv"))
            {
                Response.Write("文件不是.csv文件");
                return;
            }

            Stream stream = FileUpload1.FileContent;
            StreamReader read = new StreamReader(stream, System.Text.Encoding.GetEncoding("gb2312"));
            System.Data.DataTable dt = new System.Data.DataTable();
            int cnt = 0;
            //循环读取流数据
            while (true)
            {
                string res = read.ReadLine();
                if (res == null) break;

                string[] strs = res.Split(',');
                if (cnt == 0)
                {
                    for (int i = 0; i < strs.Length; i++)
                        dt.Columns.Add(strs[i]);
                }
                else
                {
                    System.Data.DataRow row = dt.NewRow();
                    for (int i = 0; i < strs.Length; i++)
                        row[i] = strs[i];
                    dt.Rows.Add(row);
                }
                cnt++;
            }

            //关闭流
            if (read != null)
                read.Close();

            if (null != dt && dt.Rows.Count > 0)
            {
                GridViewDL.DataSource = dt;
                GridViewDL.DataBind();
            }
        }
        catch (Exception ex) { Response.Write("读取数据异常:" + ex.Message); }

    }

你可能感兴趣的:(技术摘要-NET,stream,string,exception,null)