Read each line in file and put each line into a string

霸气de小男生 提交于 2019-12-31 05:55:52

问题


I have a text file that I want to read in and put each line from the file into its own string. So the file will have 4 lines:

2017-01-20
05:59:30
+353879833382
971575 Michael

So in the code I need to read in the file and split up each line and put them into a string i.e the first line will equal to string date, second line will equal to string time etc

Code:

public static void ParseTXTFile(string FileName, int CompanyID)
        {
            try
            {
                FileInfo file = new FileInfo(FileName);
                string Date;
                string Time;
                string Phone;
                string JobNo;
                string Name;

                using (CsvReader reader = new CsvReader(new StreamReader(FileName), false))
                {
                    while (reader.ReadNextRecord())
                    {


                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

How do I read in each line of the file and set it to a string?


回答1:


You may want to consider using the File.ReadAllLines() method which will store each line of your file into an array :

var lines = File.ReadAllLines(FileName);

You could then access each of your properties by their indices as needed :

string Date = lines[0];
string Time = lines[1];
string Phone = lines[2];
string JobNo = lines[3];
string Name = lines[4];


来源:https://stackoverflow.com/questions/41857782/read-each-line-in-file-and-put-each-line-into-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!