【问题标题】:how to read multi lines in text file in c#? [duplicate]如何在 C# 中读取文本文件中的多行? [复制]
【发布时间】:2011-02-20 18:30:16
【问题描述】:

我喜欢阅读检查文本是否有多行或单行,然后我将阅读多行并转换为单行我该怎么做?

【问题讨论】:

  • 在这种情况下什么是多行?

标签: c# text readline


【解决方案1】:

您真的不需要检查,因为File.ReadAllLines() 将始终返回一个字符串数组,而不管行数如何。您可以利用该行为,只需将返回的数组与您选择的分隔符连接起来。

string singleLine = string.Join(" ", File.ReadAllLines("filepath"));

【讨论】:

    【解决方案2】:
    string text = String.Empty;
    if(textbox.Text.Contains(Environment.NewLine))
    {
        //textbox contains a new line, replace new lines with spaces
        text = textbox.Text.Replace(Environment.NewLine, " ");
    }
    else
    {
        //single line - simply assign to variable
        text = textbox.Text;
    }
    

    【讨论】:

      【解决方案3】:

      尝试类似的方法(取决于你如何对待“线条”):

      System.IO.File.ReadAllText(path).Replace("\n\r", "");
      

      【讨论】:

      • 正确的 CRLF 应该是 "\r\n"。但更好的是Environment.NewLine
      【解决方案4】:

      这将从文本文件中读取所有行并将它们连接成一个字符串;作为分隔符:

      string[] lines = File.ReadAllLines("myfile.txt");
      string myLine = String.Join(";", lines);
      

      【讨论】:

        猜你喜欢
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-24
        • 1970-01-01
        • 2011-03-21
        • 1970-01-01
        相关资源
        最近更新 更多