2011-08-18 63 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