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

How do I use StreamReader to add split lines to a dictionary?

我正在尝试使用 StreamReader 读取 .txt 文件,拆分行并将它们添加到字典中,但是当我调试它时,它不起作用,因为第一行是空的,而且它没有继续.我如何定义字符串 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]);

您可以尝试 Linq 并让 .Net 打开(和 DisposeStreams,Readers 为您服务

 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]);

如果您坚持StreamReader,您可以实现一个简单的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]);
  } 
}

你最好这样写循环:

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

    if (fullLine == null)
        break;

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

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

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

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

  • Null is no the same thing as ""

  • Peek() will check for the next character and it the line is blank it will return "".

  • If you have lines on line 2 through X then the blank lines are not null, therefore .Peek() will return -1. Check out the documentation on it.

.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());
                }
            }

像这样更改您的代码

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

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

    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]);
    }

如果您不完全依赖使用 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]);
    }