用流读写csv文件

http://www.cnblogs.com/Clin/archive/2013/03/14/2959022.html


报错:没有权限对路径 xxx 的访问被拒绝。

解决:不能到文件夹 要指定为文件名

 DataTable dt = new DataTable();

            var filePath="@c:/";
            FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8);
            
            //excel中每一行的数据
            string strLine = "";

            //记录每行中各字段的内容
            string[] aryLine = null;
            string[] tableHead = null;

            //判断是否为第一行
            bool IsFirst = true;
            
            //计算列数
            int columnCount = 0;

            while ((strLine = sr.ReadLine())!=null) 
            {
                if (IsFirst)
                {
                    tableHead = strLine.Split(',');
                    IsFirst = false;
                    columnCount = tableHead.Length;
                    //创建列
                    for (var i = 0; i < strLine.Length - 1; i++)
                    {
                        DataColumn dc = new DataColumn(tableHead[i]);
                        dt.Columns.Add(dc);
                    }
                }
                else
                {
                    aryLine = strLine.Split(',');
                    DataRow dr = dt.NewRow();
                    for (int j = 0; j < columnCount; j++) 
                    {
                        dr[j] = aryLine[j];
                    }
                    dt.Rows.Add(dr);
                }
                if (aryLine != null && aryLine.Length > 0) 
                {
                    dt.DefaultView.Sort = tableHead[0] + " " + "asc";
                }
                sr.Close();
                fs.Close();
                return dt;


你可能感兴趣的:(C#,C#学习笔记)