【问题标题】:C# .NET StreamWriter: How to skip lines when writing file using StreamWriter?C# .NET StreamWriter:使用 StreamWriter 写入文件时如何跳过行?
【发布时间】:2011-10-29 10:14:47
【问题描述】:

我使用 StreamReader 读入一个文本文件。 我想写出这个相同的文本文件,除了它的前 4 行和最后 6 行。

我该怎么做?谢谢。

【问题讨论】:

标签: c# .net file-io streamreader streamwriter


【解决方案1】:
string[] fileLines = File.ReadAllLines(@"your file path"); 

var result = fileLines.Skip(4).Take(fileLines.Length - (4 + 6));

File.WriteAllLines(@"your output file path", result);

【讨论】:

  • 为了完整起见,应该提到SkipTake 是Linq 扩展。
【解决方案2】:

StreamReader.ReadLine() 逐行读取文件,您可以从文件中构建字符串数组。然后从数组中删除前四行和后六行。 使用StreamWriter.WriteLine(),您可以从阵列中逐行填充新文件。应该很简单。

【讨论】:

    【解决方案3】:

    似乎不是最短的方法...但它对我有用...希望它提供一些见解。

            System.IO.StreamReader input = new System.IO.StreamReader(@"originalFile.txt");
            System.IO.StreamWriter output = new System.IO.StreamWriter(@"outputFile.txt");
    
            String[] allLines = input.ReadToEnd().Split("\n".ToCharArray());
    
            int numOfLines = allLines.Length;
            int lastLineWeWant = numOfLines - (6);                  //The last index we want. 
    
            for (int x = 0; x < numOfLines; x++)
            {
                if (x > 4 - 1 && x < lastLineWeWant)  //Index has to be greater than num to skip @ start and below the total length - num to skip at end.
                {
                    output.WriteLine(allLines[x].Trim());  //Trim to remove any \r characters.
                }
            }
    
            input.Close();
            output.Close();
    

    【讨论】:

      【解决方案4】:

      这是在 VB.NET 中最简单的方法:

      Private Sub ReplaceString()
          Dim AllLines() As String = File.ReadAllLines("c:\test\myfile.txt")
          For i As Integer = 0 To AllLines.Length - 1
              If AllLines(i).Contains("foo") Then
                  AllLines(i) = AllLines(i).Replace("foo", "boo")
              End If
          Next
          File.WriteAllLines("c:\test\myfile.txt", AllLines)
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2018-08-24
        • 2016-05-03
        • 1970-01-01
        • 1970-01-01
        • 2014-02-22
        • 2014-07-27
        • 2014-06-22
        • 2020-05-23
        • 1970-01-01
        相关资源
        最近更新 更多