2011-08-18 47 views

回答

5
string[] fileLines = File.ReadAllLines(@"your file path"); 

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

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

爲了完整起見,應該提及'Skip'和'Take'是Linq擴展。 – Mrchief

+0

歡迎您編輯:) –

1

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(); 
0

這裏是做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