首页 > 代码库 > c# 读取txt文件并分隔

c# 读取txt文件并分隔

 public static List<PostPerson> GetNameByFile()
        {
            
            #region 读取txt文件
            var file = File.Open(Environment.CurrentDirectory + "\\aaa.txt",  FileMode.Open);
            List<string> txt = new List<string>();
            using (var stream = new StreamReader(file, System.Text.Encoding.GetEncoding("gb2312")))
            {
                while (!stream.EndOfStream)
                {
                    txt.Add(stream.ReadLine());
                }
            }
            file.Close();
            List<PostPerson> models = new List<PostPerson>();
            //循环list
            foreach (string item in txt)
            {
                string[] tempstr = item.Split(,);
                PostPerson model = new PostPerson();
                model.pcode = tempstr[0];
                model.pname= tempstr[1];
                models.Add(model);
            }
            // var line = 0;
            //txt.ForEach(t => {
            //    var row = 0;
            //    t.Split(‘,‘).ToList().ForEach(p => {
            //        PostPerson model = new PostPerson();
            //        model.pcode = p;
            //        row++;
            //    });
            //    line++;
            //});
            return models;
            #endregion
        }

txt文件中的格式:

xxxxxx,xxxx
xxxxxx,xxxx

 

c# 读取txt文件并分隔