修改一个文本文件的方法

目前作个项目,需要实现一个功能,就是要修改一个文本文件中的前面几行的数据,按一般的做法如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ReadLine
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load our text file
            TextReader tr = new StreamReader("test.txt");
            //How many lines should be loaded?
            int NumberOfLines = 15;
            //Make our array for each line
            string[] ListLines = new string[NumberOfLines];

            //Read the number of lines and put them in the array
            for (int i = 1; i < NumberOfLines; i++)
            {
                ListLines[i] = tr.ReadLine();
            }
            tr.Close();

            TextWriter wr = new StreamWriter("test.txt");
            ListLines[1] = "重写了";
            for (int i = 1; i < NumberOfLines; i++)
            {
                wr.WriteLine(ListLines[i]);
            }
             wr.Close();
           
        }
    }
}
这样看来,要修改一个文件首先要读取整个文件,造成了资源的浪费,目前还没找着合适的方法,只读取需要的行数,然后修改即可。

posted @ 2005-11-04 15:56  吴建明  阅读(1108)  评论(4编辑  收藏  举报