日期:2014-05-17  浏览次数:21498 次

输出字符缓冲区太小,无法包含解码后的字符
C# code

namespace FileStreamDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] m_byteData = new byte[100];
            char[] m_charData = new char[100];
            byte[] bytedata = new byte[100];

            try
            {
                //创建F:\example.txt的FileStream对象
                FileStream filestream = new FileStream(@"F:\example.txt", FileMode.OpenOrCreate);
                //将要写入的字符串转换成字符数组
                m_charData = "My first file operation".ToCharArray();


                //通过UTF-8编码方法将字符数组转换成字节数组
                Encoder encode = Encoding.UTF8.GetEncoder();
                encode.GetBytes(m_charData, 0, m_charData.Length, m_byteData, 0, true);
                //将流的当前位置设为文件开始位置
                filestream.Seek(0, SeekOrigin.Begin);
                //将字节数组中的内容写入文件
                filestream.Write(m_byteData, 0, m_byteData.Length);
                filestream.Flush();  //这句很重要,刷新,才能将内存中的数据真正的写入文件中
                filestream.Close();
                Console.WriteLine("write to file Succeed!");

                FileStream readstream = new FileStream(@"F:\example.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                readstream.Seek(0, SeekOrigin.Begin);
                readstream.Read(bytedata, 0, 100);
                Decoder m_Dec = Encoding.UTF8.GetDecoder();
                m_Dec.GetChars(bytedata, 0, bytedata.Length, m_charData, 0);
                Console.WriteLine("Read From File Succeed!");
                Console.WriteLine(m_charData);
            }
            catch (IOException ex)
            {
                Console.WriteLine("There is an IOException");
                Console.WriteLine(ex.Message);

            }

              
                Console.ReadLine();
        }
    }
}




 m_Dec.GetChars(bytedata, 0, bytedata.Length, m_charData, 0);
这句抛异常,“输出字符缓冲区太小,无法包含解码后的字符,编码“Unicode (UTF-8)”的操作回退“System.Text.DecoderReplacementFallback”。”
各位高手,这个是什么原因啊。