我如何使用StreamReader将分割线添加到字典?

问题描述 投票:0回答:6

我正在尝试使用StreamReader读取.txt文件,分割行并将其添加到Dictionary中,但是当我对其进行调试时,它不起作用,因为第一行为null,并且无法继续进行。如何定义字符串fullLine使其起作用?

        StreamReader sr = new StreamReader(@"N:\Desktop\krew.txt");
        StreamWriter sw = new StreamWriter(@"N:\Desktop\newKrew.txt");
        Dictionary<string, string> dict = new Dictionary<string, string>();
        string fullLine = "";


        while (fullLine != null)
        {
            fullLine = sr.ReadLine();
            string[] wholeLine = fullLine.Split('\t');
            dict.Add(wholeLine[0], wholeLine[1]);
c# split streamreader
6个回答
2
投票

尝试使用波纹管。这会将line变量设置为文件中的每一行

    StreamReader sr = new StreamReader(@"N:\Desktop\krew.txt");
    Dictionary<string, string> dict = new Dictionary<string, string>();
    string line;

    while ((line = sr.ReadLine()) != null)
    {
        string[] wholeLine = line.Split('\t');
        dict.Add(wholeLine[0], wholeLine[1]);
    }

1
投票

您最好像这样编写循环:

while (true)
{
    string fullLine = sr.ReadLine();

    if (fullLine == null)
        break;

    string[] wholeLine = fullLine.Split('\t');
    dict.Add(wholeLine[0], wholeLine[1]);
    ...

如您现在所写的循环,fullLine在文件末尾将为空,然后fullLine.Split('\t');将抛出NullReferenceException

[我怀疑这就是您说first line is null and it doesn't go further时的意思。因为您将fullLine初始化为“”,所以它实际上不是导致问题的first行,但是我认为这是潜在的问题。


1
投票

在while循环中使用.Peek()方法读取到文件末尾。它应该超过您的第一行为空。

  • Null与“”

  • 的不同
  • Peek()将检查下一个字符,并且该行是blank,它将返回""

  • 如果您在第2行到X中有行,则空白行不为null,因此.Peek()将返回-1。查看有关文档。

。Peek()https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader.peek?view=netframework-4.8

//Doing it in a Using statement to properly dispose of the StreamReader
using (StreamReader sr = new StreamReader(path)) 
            {

                while (sr.Peek() > -1) 
                {
                    Console.WriteLine(sr.ReadLine());
                }
            }

1
投票

您可以尝试Linq并让.Net打开(和DisposeStream,为您提供Reader

 using System.Linq;

 ...

 Dictionary<string, string> dict = File
   .ReadLines(@"N:\Desktop\krew.txt")
   .Where(line => !string.IsNullOrEmpty(line)) // to be on the safe side
   .Select(line => line.Split('\t'))
   .ToDictionary(items => items[0], items => items[1]);

添加到现有字典中:

 var lines = File
   .ReadLines(@"N:\Desktop\krew.txt")
   .Where(line => !string.IsNullOrEmpty(line))
   .Select(line => line.Split('\t'));

 foreach (var wholeLine in lines)
   dict.Add(wholeLine[0], wholeLine[1]);

如果您在StreamReaderinsist,则可以实现一个简单的for循环:

// Do not forget to Dispose it
using (StreamReader sr = new StreamReader(@"N:\Desktop\krew.txt")) {
  // if fullLine == null, sr is at the end and can't read any more lines
  for (string fullLine = sr.ReadLine(); fullLine != null; fullLine = sr.ReadLine()) {
    string[] wholeLine = fullLine.Split('\t');
    dict.Add(wholeLine[0], wholeLine[1]);
  } 
}

0
投票

像这样更改您的代码

while ((fullLine = sr.ReadLine()) != null)
        {
            string[] wholeLine = fullLine.Split('\t');
            dict.Add(wholeLine[0], wholeLine[1]);
        }

0
投票

如果您不是完全依赖具有来使用StreamReader。。

    string[] read = File.ReadAllLines(filepath);
    for (int i = 0; i < read.Length; i++)
    {
        if (string.IsNullOrEmpty(read[i])
            continue;
        string[] lineArray = read[i].Split(new [] {" "}, StringSplitOptions.None);
        dict.Add(lineArray[0], lineArray[1]);
    }
© www.soinside.com 2019 - 2024. All rights reserved.