msdn解析
解决方法,应使用 Read 方法并将已读取的字符存储在预先分配的缓冲区内。
但是我找了找,没找到参考代码。
我出现问题的代码如下,打开,写入文件,在读写超过30M-50M以上的txt文件时出现OutOfMemoryException。
请教无OutOfMemoryException错误的代码。button1.Text = "正在提取";
            openFileDialog1.ShowDialog();
            saveFileDialog1.ShowDialog();
            StreamReader sr = new StreamReader(openFileDialog1.FileName);
            StreamWriter SW = new StreamWriter(saveFileDialog1.FileName, true);            string s = sr.ReadToEnd();
            string pattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            //Regex   reg   =   new   Regex(ex,RegexOptions.IgnoreCase   );
            foreach (Match m in Regex.Matches(s, pattern))
            {
                string mk1 = m.Groups[0].Value;
                SW.WriteLine(mk1);
            }
            
            //fs.Close();
            sr.Close();
            SW.Close();
            button1.Text = "开始提取";
            MessageBox.Show("提取完成");
            

解决方案 »

  1.   

    当需要从流的当前位置到末尾读取所有输入时,ReadToEnd 的性能最佳。如果需要对从流中读取的字符数进行进一步的控制,请使用 Read(Char[],Int32,Int32) 方法重载,它通常可达到更佳的性能。......请注意,当使用 Read 方法时,使用大小与流的内部缓冲区相同的缓冲区会更有效。如果构造流时未指定缓冲区大小,则缓冲区的默认大小为 4 KB(4096 字节)。这里写的很清楚了...而且还带着示例
    using System;
    using System.IO;class Test 
    {

        public static void Main() 
        {
            string path = @"c:\temp\MyTest.txt";        try 
            {
                if (File.Exists(path)) 
                {
                    File.Delete(path);
                }            using (StreamWriter sw = new StreamWriter(path)) 
                {
                    sw.WriteLine("This");
                    sw.WriteLine("is some text");
                    sw.WriteLine("to test");
                    sw.WriteLine("Reading");
                }            using (StreamReader sr = new StreamReader(path)) 
                {
                    //This is an arbitrary size for this example.
                    char[] c = null;                while (sr.Peek() >= 0) 
                    {
                        c = new char[5];
                        sr.Read(c, 0, c.Length);
                        //The output will look odd, because
                        //only five characters are read at a time.
                        Console.WriteLine(c);
                    }
                }
            } 
            catch (Exception e) 
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
        }
    }