Exemplo n.º 1
0
        public static List <string> ReadFileByRead(string filepath)
        {
            var encoding = FileEncoding.GetType(filepath);

            List <string> lstmsg = new List <string>();

            using (StreamReader sr = new StreamReader(filepath, encoding))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line.ToString());
                    lstmsg.Add(line.ToString());
                }
            }

            ReadFileByStream(filepath);

            return(lstmsg);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 读取文件数据(使用流)
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        private static List <string> ReadFileByStream(string filepath)
        {
            var encoding = FileEncoding.GetType(filepath);

            List <string> lstmsg     = new List <string>();
            string        fullstring = "";

            using (FileStream fsRead = File.OpenRead(filepath))
            {
                byte[] buf   = new byte[1024 * 8];
                int    total = 0;
                int    size  = 0;
                do
                {
                    //注意第二个参数是在buffer中的偏移量,不是在文件中的偏移量
                    size = fsRead.Read(buf, 0, buf.Length);


                    //默认
                    //fullstring += encoding.GetString(buf);
                    //改为过滤BOM转换方法
                    fullstring += GetUTF8String(buf);

                    total += size;
                } while (size > 0);

                if (total != fsRead.Length)
                {
                    Console.WriteLine("Error: total != fsRead.Length");
                }

                fsRead.Close();
            }

            lstmsg = fullstring.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            return(lstmsg);
        }