将文本写入文件的中间

时间:2009-01-04 02:50:27

标签: c#

有没有办法可以从文件中的某个位置将文字写入文件?

例如,我打开一个包含10行文本的文件,但我想在第5行写一行文字。

我想一种方法是使用readalllines方法将文件中的文本行作为数组返回,然后在数组中的某个索引处添加一行。

但有一个区别是,某些集合只能添加成员到最后,有些集合可以在任何目的地添加。要仔细检查,数组总是允许我在任何索引处添加一个值,对吧? (我敢肯定我的一本书说其他明智的。)

此外,还有更好的方法吗?

由于

3 个答案:

答案 0 :(得分:3)

哦,叹了口气。查找“主文件更新”算法。

这是伪代码:

open master file for reading.
count := 0
while not EOF do
    read line from master file into buffer
    write line to output file    
    count := count + 1
    if count = 5 then
       write added line to output file
    fi
od
rename output file to replace input file

答案 1 :(得分:1)

如果您正在读/写小文件(例如,20兆字节以下 - 是的,我认为20M“小”)并且不经常写(如同,而不是每秒几次),那么只需读/写整件事。

文本文档等串行文件不是为随机访问而设计的。这就是数据库的用途。

答案 2 :(得分:1)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class Class1
{                     
    static void Main()
    {
        var beatles = new LinkedList<string>();
        beatles.AddFirst("John");                        
        LinkedListNode<string> nextBeatles = beatles.AddAfter(beatles.First, "Paul");
        nextBeatles = beatles.AddAfter(nextBeatles, "George");
        nextBeatles = beatles.AddAfter(nextBeatles, "Ringo");

        // change the 1 to your 5th line
        LinkedListNode<string> paulsNode = beatles.NodeAt(1); 
        LinkedListNode<string> recentHindrance = beatles.AddBefore(paulsNode, "Yoko");
        recentHindrance = beatles.AddBefore(recentHindrance, "Aunt Mimi");
        beatles.AddBefore(recentHindrance, "Father Jim");

        Console.WriteLine("{0}", string.Join("\n", beatles.ToArray()));
        Console.ReadLine();                       
    }
}

public static class Helper
{
    public static LinkedListNode<T> NodeAt<T>(this LinkedList<T> l, int index)
    {
        LinkedListNode<T> x = l.First;

        while ((index--) > 0) x = x.Next;

        return x;
    }
}
相关问题