2009-11-02 32 views
2

好一个文本文件,所以我有示例内容如下管理在C#

line1with some random stuff here 
line 2 with something very completely different 
line3 has some other neat stuff 
line4 is the last line in the textfile 

一个文本文件,我需要得到该文本文件,删除一行,并保留文件的其余部分完好无损。所以如果我想删除第2行,id想要这样的结果:

line1with some random stuff here 
line3 has some other neat stuff 
line4 is the last line in the textfile 

通知我不想在行之间留下任何空格。

〜代码示例请!即使这是不可能的,任何帮助将不胜感激! :)

+0

删除一行,并将文件保留为机智:这是矛盾的 – 2009-11-02 03:04:20

+4

您真的无法弄清楚他的意思而不玩弄语义吗? – Tinister 2009-11-02 03:10:03

+0

好吧,我看不出原来的文件是否被留下,而另一个创建的文件或修改后的文件替换了第一个。 – 2009-11-02 03:22:38

回答

5

做最简单的方法是这样的:

string filePath = ... 
List<string> lines = new List<string>(File.ReadAllLines(filePath)); 
lines.RemoveAt(2); //Remove the third line; the index is 0 based 
File.WriteAllLines(filePath, lines.ToArray()); 

注意,这将是对于大文件非常低效的。

2

假设你有一个lineIsGood方法,该方法确定给定的行是否是你想要保留的行(在你的情况下,你可以检查它是否不是第二行,但我假设你' ð最终需要更严格的标准):

Queue<string> stringQueue = new Queue<string(); 
string tempLine = ""; 

StreamReader reader = new StreamReader(inputFileName); 
do 
{ 
    tempLine = reader.ReadLine(); 
    if (lineIsGood(tempLine)) 
    { 
      stringQueue.Enqueue(tempLine); 
    } 
} 
while(reader.Peek() != -1); 
reader.Close(); 

StreamWriter writer = new StreamWriter(inputFileName);  
do 
{ 
    tempLine = (string) stringQueue.Dequeue(); 
    writer.WriteLine(tempLine);   
} 
while (stringQueue.Count != 0); 
writer.Close(); 
+0

这将在不清除文件的情况下追加行。您需要写入临时文件,然后用它替换原始文件。 – SLaks 2009-11-02 03:15:13

+0

在同一个文件上有读写器是否真的有效?我不会期望它。 – Tinister 2009-11-02 03:16:20

+0

我还没有尝试过,但我认为它会起作用,因为它们不在同一个流中。但是,正如我上面提到的那样,它不会做他想做的事。 – SLaks 2009-11-02 03:17:41

0

也许使用StreamWriter.Write(char [] buffer,int index,int count)过载。

它具有能够在文件中的某一点开始写入的优点。所以你所需要做的就是读取行数并计算你传递的字符数,读入你想要改变的行,得到它的长度然后像这样使用它

StreamWriter.Write(NewLine.CharArray(), CharCount,LineLength)