从文本文件中解析行

时间:2016-01-06 21:27:32

标签: c# streamreader

我正在阅读相同文本文件input.txt的2个输入参数,这些文件使用'#'分隔,如:

  

12#15

     

17#77

     

31#12

我使用过这种语法,但它只读取最后一行。为什么它不起作用?什么是读取直线的最佳循环条件,如12 + 15和显示27并读取下一行17 + 71并显示88和最后处理

            StreamReader reader = new StreamReader("input.txt");
            string line;
            int count = 0;
            while ((line = reader.ReadLine()) != null)
            {
                string[] splitted = line.Split('#');
                string first = splitted[0].Trim();
                string second = splitted[1].Trim();
                x = Convert.ToInt32(first);
                y = Convert.ToInt32(second);

请使用StreamReader语法帮助我。

1 个答案:

答案 0 :(得分:4)

简而言之,您可以使用StreamReader阅读文件的行,然后使用string.Split()int.Parse()方法提取数据。

您可以使用StreamReader将文件读入字符串。

string text;
using (StreamReader sr = new StreamReader("file.txt"))
    text = sr.ReadToEnd();
string[] parts = text.Replace("\r", string.Empty).Split('#', '\n');
txtA.Text = (int.Parse(parts[0]) + int.Parse(parts[1]).ToString();
txtB.Text = (int.Parse(parts[2]) + int.Parse(parts[3]).ToString();