TXT文件中已存在多行内容,怎么在起始位置再增加一行新的数据?然后怎么知道这个文档共多少行?因为文档行数比较多,我想分页显示。请大家指点,谢谢

解决方案 »

  1.   

    知道文档有多行,可以一个个char读判断  '\r' 的次数, => 行数
    分页显示的话,通过设置 FileStream 的位置可以实现
      

  2.   

    List<string> lines = new List<string>(File.ReadAllLines("")); 
    lines.Count
    File.WriteAllText
    File.AppendAllText
      

  3.   

    先全部读出来,从新New一个文件,写你要的内容之后,在将刚才读到的内容追加到文件中。
    当然这样效率很差。
    想要性能好,就需要自己定义文件结构来实现快速索引,以及添加等功能。
      

  4.   


    正解要是文件太大的话,可以用流拷贝的方法,争个苦劳吧
    using (FileStream src = new FileStream("文件名", FileMode.Open))
    {
        using (FileStream dst = new FileStream("临时文件名", FileMode.Create))
        {
            byte[] buffer = new byte[1024];
            int len;        //首先写要添加的内容
            byte[] added = Encoding.Default.GetBytes("要添加的内容\r\n");
            dst.Write(added, 0, added.Length);        //把原有内容写入
            while ((len = src.Read(buffer, 0, buffer.Length)) != 0)
                dst.Write(buffer, 0, len);        dst.Close();
        }
        src.Close();
    }
    //删除原文件
    File.Delete("文件名");
    File.Move("临时文件名", "文件名");
      

  5.   

    对于后一问,3楼的方法是可以,但文件较大时,比较吃内存这个方法是麻烦了点,但效果还是不错的
    int count = 0;
    using (StreamReader reader = new StreamReader(new FileStream("文件名", FileMode.Open)))
    {
        string line;
        while ((line = reader.ReadLine()) != null) count++;
        reader.Close();
    }
      

  6.   

    为已存在的Text文件添加一行新内容using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml;
    using System.Collections;
    using System.IO;namespace ConsoleApplication1
    {
        class Program
        {        public Program()
            {
                string lastText=ReadEntireText();
                Console.WriteLine("----------------------------------------");
                //Overwrite the exist file--1.txt
                using (StreamWriter sw = new StreamWriter("1.txt", false))
                {
                    //"NewLine\r\n"为你想要添加的存放在文本文件首行的内容
                    sw.WriteLine("New Line\r\n" + lastText);
                }
                ReadEntireText();
            }        public static string ReadEntireText()
            {
                string all;
                using (StreamReader sr = new StreamReader("1.txt"))
                {
                    all = sr.ReadToEnd();
                    Console.WriteLine(all);
                }
                return all;
            }        static void Main(string[] args)
            {
                Program p1 = new Program();
                Console.ReadLine();
            }
        }
    }