读取行,用定界符分隔单词,将每个单词写在新行上,然后移至下一行

Read line, seperate words by delimiter, write each word on new line, then move on to the next line

标题有点长,但我会在这里解释一下。

我有一个名为 sample.txt

的文本文件

sample.txt

"105"|2015-01-01 00:00:00|"500"|John Smith"|"Facebook"|"Ohio"|"(555) 555-5555"
"110"|2016-05-20 01:40:00|"550"|David K"|"Twitter"|"Missouri"|"(555) 555-5555"

我的目标是读取此文件,用定界符分隔单词并在新行中吐出每个字段。我设法做到了,但我不知道如何让它移到下一行。

目前它做我想做的事,但只针对第一行。我以为 line = sr.ReadLine() 会进入下一组,但事实并非如此。

String line;
try
{
    StreamReader sr = new StreamReader("C:\Users\ME\Documents\sample.txt");

    line = sr.ReadLine();
    char delimiterChar = '|';

    while (line != null)
    {
        string[] words = line.Split(delimiterChar);
        foreach (string s in words)
        {
            Console.WriteLine(s);
            line = sr.ReadLine();
         }
     }

     sr.Close();
     Console.ReadLine();
}
catch (Exception e)
{
    Console.WriteLine("Exception: " + e.Message);
    Console.ReadKey();
}
finally
{
    Console.WriteLine("Executing Finally Block");
    Console.ReadKey();
}

您需要将 line = sr.ReadLine(); 移出 foreach 循环。现在它正在为第一行中的每个字符串读取一个新行,这会消耗其余的输入。

它应该紧接在 foreach 循环之后,但仍在 while 循环内。