【发布时间】:2011-10-29 10:14:47
【问题描述】:
我使用 StreamReader 读入一个文本文件。 我想写出这个相同的文本文件,除了它的前 4 行和最后 6 行。
我该怎么做?谢谢。
【问题讨论】:
标签: c# .net file-io streamreader streamwriter
我使用 StreamReader 读入一个文本文件。 我想写出这个相同的文本文件,除了它的前 4 行和最后 6 行。
我该怎么做?谢谢。
【问题讨论】:
标签: c# .net file-io streamreader streamwriter
string[] fileLines = File.ReadAllLines(@"your file path");
var result = fileLines.Skip(4).Take(fileLines.Length - (4 + 6));
File.WriteAllLines(@"your output file path", result);
【讨论】:
Skip 和Take 是Linq 扩展。
StreamReader.ReadLine() 逐行读取文件,您可以从文件中构建字符串数组。然后从数组中删除前四行和后六行。
使用StreamWriter.WriteLine(),您可以从阵列中逐行填充新文件。应该很简单。
【讨论】:
似乎不是最短的方法...但它对我有用...希望它提供一些见解。
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();
【讨论】:
这是在 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
【讨论】: