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

时间:2019-12-11 14:51:36

标签: c# split streamreader

我试图用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]);

6 个答案:

答案 0 :(得分: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 :(得分:1)

您可以尝试使用 Linq 并让.Net打开(和DisposeStream s,Reader s

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

答案 2 :(得分: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 行,但是我认为这是潜在的问题。

答案 3 :(得分:1)

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

  
      
  • 空与“”不一样。

  •   
  • Peek()将检查下一个字符,并且该行是<style>,它将返回blank

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

  •   

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

""

答案 4 :(得分:0)

像这样更改代码

// Change return value to int
int squareRoot(float number1, float *squareroot)
{  [....] }

int main(void)
{
    [...]

    // Declare a variable to hold the return value.
    int retValue;
    float squareRootResult;

    // Put the return value in variable retValue
    retValue = squareRoot(n1, &squareRootResult);

    // Check the value that was returned!
    if (retValue == 1)
    {
        printf("The squareroot of the entered number is: %f", squareRootResult);
    }
    else if (retValue == 0)
    {
        printf("It is not possible to calculate thesquare root of a negative number​");
    }

答案 5 :(得分: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]);
    }