我需要用C#读取一个超大的TXT文档到程序中(800M),使用普通的方式直接会照成错误,缓冲区和数据流相关的知识不是很懂,有没人讲解下?

解决方案 »

  1.   

    用TextReader 和TextWriter去读和写
    类似 游标读取,不会把文件都加载到内存
    可以MSDN到这两个类,微软的代码很清楚 
      

  2.   

    我读取文件一直都是用的System.IO.File.ReadAllText
    TextReader 没用过,可以说下简单的使用方法?
      

  3.   

    using System;
    using System.IO;class Test 
    {
        public static void Main() 
        {
            try 
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader("TestFile.txt")) 
                {
                    String line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null) 
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception e) 
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
    }
     
    这是MSDN里的方法
      

  4.   

    using System;
    using System.IO;class TextRW
    {
        static void Main()
        {
            TextWriter stringWriter = new StringWriter();
            using(TextWriter streamWriter = 
                new StreamWriter("InvalidPathChars.txt"))
            {
                WriteText(stringWriter);
                WriteText(streamWriter);
            }        TextReader stringReader = 
                new StringReader(stringWriter.ToString());
            using(TextReader streamReader = 
                new StreamReader("InvalidPathChars.txt"))
            {
                ReadText(stringReader);
                ReadText(streamReader);
            }
        }    static void WriteText(TextWriter textWriter)
        {
            textWriter.Write("Invalid file path characters are: ");
            textWriter.Write(Path.InvalidPathChars);
            textWriter.Write('.');
        }    static void ReadText(TextReader textReader)
        {
            Console.WriteLine("From {0} - {1}", 
                textReader.GetType().Name, textReader.ReadToEnd());
        }
    }
      

  5.   

    wangsunjun大大很给力!多谢指点!