コード例 #1
0
ファイル: SafeC.cs プロジェクト: baixue001/IPS
        public static string ReadFileStr(string vpath, bool lines = false)
        {
            FileEncodeHelper fileEncodeHelper = new FileEncodeHelper();

            vpath = vpath.ToLower();
            if (Enumerable.Count <string>((IEnumerable <string>)BanRead, (Func <string, bool>)(p => vpath.IndexOf(p) > -1)) > 0)
            {
                throw new Exception("该文件不允许读取!");
            }
            string str1 = IOPath.VToP(vpath);

            if (!File.Exists(str1))
            {
                throw new Exception(vpath + "文件不存在!");
            }
            if (!lines)
            {
                return(File.ReadAllText(str1, fileEncodeHelper.GetType(str1)));
            }
            string str2 = "";

            foreach (string str3 in File.ReadLines(str1, fileEncodeHelper.GetType(str1)))
            {
                str2 = str2 + str3 + "<br/>";
            }
            return(str2);
        }
コード例 #2
0
    /// <summary>
    /// 将CSV文件的数据读取到DataTable中
    /// </summary>
    /// <param name="vpath">CSV文件虚拟路径</param>
    /// <returns>返回读取了CSV数据的DataTable</returns>
    public DataTable OpenCSV(string vpath)
    {
        string       ppath    = function.VToP(vpath);
        Encoding     encoding = new FileEncodeHelper().GetType(ppath);
        DataTable    dt       = new DataTable();
        FileStream   fs       = new FileStream(vpath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        StreamReader sr       = new StreamReader(fs, encoding);
        //string fileContent = sr.ReadToEnd();
        //encoding = sr.CurrentEncoding;
        //记录每次读取的一行记录
        string strLine = "";

        //记录每行记录中的各字段内容
        string[] aryLine   = null;
        string[] tableHead = null;
        //标示列数
        int columnCount = 0;
        //标示是否是读取的第一行
        bool IsFirst = true;

        //逐行读取CSV中的数据
        while ((strLine = sr.ReadLine()) != null)
        {
            if (IsFirst == true)
            {
                tableHead   = strLine.Split(',');
                IsFirst     = false;
                columnCount = tableHead.Length;
                //创建列
                for (int i = 0; i < columnCount; 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);
    }