【问题标题】:Having issues using Streamreader to skip lines in C#在 C# 中使用 Streamreader 跳过行时遇到问题
【发布时间】:2016-07-23 18:13:32
【问题描述】:

我在使用C# 中的Streamreader 读取文件时遇到问题,其中我正在读取的文件中的换行符 也被读入我的程序并导致进一步的问题在代码中打开。

以下是我尝试读取的文件的示例。

Example,1,2,3
    <--- // Trying to skip these lines.
    <--- // Trying to skip these lines.
// MY COMMENTS.

下面是我目前用来检查换行符的代码。

if (line.StartsWith("//") || 
    line.StartsWith("\r\n") || 
    line.StartsWith("\n") || 
    line.StartsWith("\r") || 
    line.StartsWith(" ") || 
    line.StartsWith(Environment.NewLine) || 
    line.StartsWith(Environment.NewLine) || 
    line.StartsWith($" {Environment.NewLine}")) {

    // SKIP THE LINE.
    break;
}
// ADD TO ARRAY

我尝试在if statement 中检查line.StartsWith(""), 但这会导致没有值被添加到我的数组中。

要跳过这些行,我需要进行哪些更改?

【问题讨论】:

    标签: c# streamreader


    【解决方案1】:

    https://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx

    行定义为一系列字符,后跟换行符 ("\n")、回车 ("\r") 或立即回车 后跟换行符 ("\r\n")。 返回的字符串不 包含终止的回车或换行。返回的 如果到达输入流的末尾,则值为 null。

    这篇文章可能会有所帮助:http://www.dotnetperls.com/empty-string

    并尝试使用line.IsNullOrEmpty()(假设您读取的行上没有其他隐藏空格)。

    理论上,每个字符串都“以”开头,因此“”将与您读入的每一行/字符串匹配。

            if ("Hello, World!".StartsWith(""))
                Console.WriteLine("Hello, World!");
            return;
    

    打印出声明。

    【讨论】:

    • 完美!谢谢。
    【解决方案2】:

    即使你有一个答案(几个),我也会选择一些感觉更“干净”的东西。

    // Read all your lines:
    string source = System.IO.File.ReadAllText(path_to_your_file);
    
    // Split them on new lines, ignore any empty lines
    var lines = source.Split(Environment.NewLine.ToCharArray()
                            , StringSplitOptions.RemoveEmptyEntries );
    
    // Iterate over your `lines` here
    // ...
    

    【讨论】:

      【解决方案3】:

      你试过string.IsNullOrWhiteSpace(stringValue)吗?你使用'StreamReader.ReadLine()'吗?返回的字符串不包含换行符。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-21
        • 2013-02-25
        • 2015-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多