如何在使用紧凑框架 3.5 读取文件时跳过行

How to skip lines while reading in a file using compact framework 3.5

我有一个 Windows 表单应用程序,我使用 Compact Framework 3.5 重写了它。在原来的应用程序中,我有一段代码,我曾经在文件中读取它并跳过它的前 4 行。

这是运行良好的代码块:

var openFile = File.OpenText(fullFileName);
            var fileEmpty = openFile.ReadLine();
            if (fileEmpty != null)
            {
                var lines = File.ReadAllLines(fullFileName).Skip(4); //Will skip the first 4 then rewrite the file
                openFile.Close();//Close the reading of the file
                File.WriteAllLines(fullFileName, lines); //Reopen the file to write the lines
                openFile.Close();//Close the rewriting of the file
            } 

我不得不重写上面的代码,因为它不能像在 Compact Framework 中那样使用。

这是我的代码:

var openFile = File.OpenText(fullFileName);
            var fileEmpty = openFile.ReadLine();
            if (fileEmpty != null)
            {
                var sb = new StringBuilder();
                using (var sr = new StreamReader(fullFileName))
                {
                    string line1;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line1 = sr.ReadLine().Skip(4).ToString()) != null) //Will skip the first 4 then rewrite the file
                    {
                        sb.AppendLine(line1);
                    }
                }

然而,当我 运行 以上内容时,我收到关于 (while ((line1 = sr.ReadLine().Skip(4).ToString()) != null)) ArgumentNullException 未处理且值不能为空的错误。

谁能告诉我如何在紧凑型框架中做到这一点?

由于 sr.ReadLine() return 是一个字符串,这将跳过字符串中的前四个字符,return 其余的作为字符数组,然后调用 ToString() 就可以了...不是你想要的。

sr.ReadLine().Skip(4).ToString()

你得到 ArgumentNullException 的原因是因为 sr.ReadLine() 最终 return 是一个 null 字符串,当你试图跳过字符串的前四个字符时null 字符串,它抛出,正如您通过查看 Skip():

的实现所看到的
public static IEnumerable<TSource> Skip<TSource>(this IEnumerable<TSource> source, int count)
{
    if (source == null)
        throw new ArgumentNullException("source");

    return SkipIterator<TSource>(source, count);
}

保持大部分代码不变,您可以只阅读前几行而不对它们进行任何操作(假设文件中肯定至少有 4 行)。

using (var sr = new StreamReader(fullFileName))
{
    // read the first 4 lines but do nothing with them; basically, skip them
    for (int i=0; i<4; i++)
        sr.ReadLine();

    string line1;

    while ((line1 = sr.ReadLine()) != null)
    {
        sb.AppendLine(line1);
    }
}