Write / WriteLine奇怪的行为

时间:2018-01-08 10:50:02

标签: c# file stream

我想要读取类似ini的文件结构:

[section1]
param1=value1
param2=value2
etc...

这里是代码:

string inputLine;
// Read and display lines from the file until the end of 
// the file is reached.
while ((inputLine = sr.ReadLine()) != null)
{
    Console.WriteLine(inputLine);
    {
        string[] values = inputLine.Split(new Char[] { '=' });
        Console.WriteLine(values[0]);
        Console.WriteLine(values[1]);
    }
}

我的问题是,如果我删除所有[section]部分,我可以很好地阅读所有参数。但如果我决定保留它们,Console.Write(inputLine)Console.Write就会失败。我也尝试了Console.Write(inputLine[0])并且它也给了我一个错误,这让我认为[字符是某种方式的问题......

Write / WriteLine只是一个测试机制,我最终想要的是char.IsLetter(inputStream[0])来检查该行的第一个字符是否是一个字母,如果是,请跳过它,因为我是只是想读取参数的键值对。

3 个答案:

答案 0 :(得分:0)

问题是,当values分割的链接[section]导致单项数组时,您正尝试读取数组=中的第二项。您可以跳过以[开头的所有行来解决此问题:

string inputLine;
// Read and display lines from the file until the end of 
// the file is reached.
while ((inputLine = sr.ReadLine()) != null)
{
    if (String.IsNullOrEmpty(inputLine) || inputLine.StartsWith("[")) {
        continue;
    }

    Console.WriteLine(inputLine);
    {
        string[] values = inputLine.Split(new Char[] { '=' });
        Console.WriteLine(values[0]);
        Console.WriteLine(values[1]);
    }
}

答案 1 :(得分:0)

部分之间是否有空行? 因为这是你在inputLine [0]上得到错误的地方。

答案 2 :(得分:0)

在尝试访问您尝试从中解析的任何值之前,您应该验证您读取的行是否有数据,否则您可能会收到类似其他2个答案所指示的错误(因为只解析了1个值或从该行读取的0个字符。)

string testInput =
   "[section1]\r\n" +
   "param1=value1\r\n" +
   "param2=value2\r\n\r\n" +
   "[section2]\r\n" +
   "parama=valuea";

using (var reader = new System.IO.StringReader(testInput))
{
   string inputLine;
   while ((inputLine = reader.ReadLine()) != null)
   {
      string[] values = inputLine.Split(new char[] {'='}, 2);
      if (values.Length > 1)
      {
         Console.WriteLine("Value of {0} is {1}", values[0], values[1]);
      }
      else
         Console.WriteLine("\"{0}\" has {1} characters and {2} values on it", inputLine, inputLine.Length, values.Length);       }
}

输出结果为:

"[section1]" has 10 characters and 1 values on it
Value of param1 is value1
Value of param2 is value2
"" has 0 characters and 1 values on it
"[section2]" has 10 characters and 1 values on it
Value of parama is valuea