原文网址:http://www.blogwind.com/Wuvist/42999.shtml

 

在.Net framework中StreamReader的使用encoding必须在构造器中指定,而且中途完全不可以更改。

在一般的情况下,这不会造成什么问题。一般若是从硬盘读取文件,单一文件内的编码一般都是统一的。即便是发现读错,亦可以关闭StreamReader,重启使用新的编码读取。

偏偏偶最近遇到了需要修改编码的需求,而且,我的程序没有关闭重读的机会。因为偶使用的StreamReader的BaseStream是一个Network Stream,我不可以关闭它……但是Network Stream传过来的东西很可能包涵不同的编码……GB2312,Big5,UTF8,ISO-8859-1等等……虽然是先得到编码信息,然后再读具体内容,但是,一开始使用的Stream Reader编码一旦错了,读出来的东西便再也无法恢复……会丢字之类的……

我也不可以在获得编码信息之后,重新建立一个新的Stream Reader,因为具体内容已经被原来的Stream Reader给缓冲掉了……

唯一的解决方法,便是自己实现一个可以改变CurrentEncoding属性的Stream Reader了……

全部从头写起非常不实际,偶是先当了mono源码,从mono的Stream Reader实现代码做修改。

Stream Reader其实很简单,它内部有两个Buffer,一个是input buffer,一个是decoded buffer,前者用于缓存从base stream读过来的原始数据,后者用于缓存根据原始数据解码出来后的东西……只要看明白mono的实现中ReadBuffer这个方法,要动态修改CurrentEncoding也就不是太难了……

我需要处理的网络协议是一个行协议……偶在程序中只调用了StreamReader的Readline方法,而完全没有使用Read的两个方法,这也使得偶动态修改编码容易了许多……

偶的做法是每次调用Readline的时候,不仅移动decoded buffer的游标(pos),同时也移动input buffer一个新的游标(pos_input),做法很简单,Readline方法需要调用FindNextEOL移动游标查找换行符号……我在FindNextEOL方法添加多一行:
int FindNextEOL ()
{
FindNextInputEOL();
....

而FindNextInputEOL这个新的函数,完全是FindNextEOL的翻版,只是前者处理input buffer,而后者处理decoded buffer……

如此一来,我便可以知道每次Readline之后,input buffer中还没有被上层读到的原始数据有哪些了……

然后,再把CurrentEncoding属性添加Set的方法:
set
{
encoding=value;
decoder = encoding.GetDecoder();
decoded_count = pos + decoder.GetChars (input_buffer, pos_input, cbEncoded , pos_input, decoded_buffer, pos);
}

设定新编码时,程序便根据input buffer的游标(pos_input)把没有被读到的原始数据重新decode一次,并且替换掉decoded buffer中的内容。

然后,事情就搞定了……甚至不需要对Readline方法做任何修改……除了把cbEncoded这个变量放到全局里面外……

但是,偶这个修改使得Read的两个方法变得完全不可以用……一旦调用了……便会使得input buffer与decoded buffer里面两个游标不同步……下面附上完整的代码,还望有大侠可以帮忙把Read的两个方法也给搞定了…… 先谢过……
 

 
  
  1. /  
  2. // System.IO.StreamReader.cs  
  3. //  
  4. // Author:  
  5. //   Dietmar Maurer (dietmar@ximian.com)  
  6. //   Miguel de Icaza (miguel@ximian.com)   
  7. //  
  8. // (C) Ximian, Inc.  http://www.ximian.com  
  9. // Copyright (C) 2004 Novell (http://www.novell.com)  
  10. //  
  11.  
  12. //  
  13. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)  
  14. //  
  15. // Permission is hereby granted, free of charge, to any person obtaining  
  16. // a copy of this software and associated documentation files (the  
  17. // "Software"), to deal in the Software without restriction, including  
  18. // without limitation the rights to use, copy, modify, merge, publish,  
  19. // distribute, sublicense, and/or sell copies of the Software, and to 
  20. // permit persons to whom the Software is furnished to do so, subject to 
  21. // the following conditions:  
  22. //   
  23. // The above copyright notice and this permission notice shall be  
  24. // included in all copies or substantial portions of the Software.  
  25. //   
  26. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  
  27. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
  28. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
  29. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE  
  30. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
  31. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROMOUT OF OR IN CONNECTION 
  32. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.  
  33. //  
  34.  
  35. using System;  
  36. using System.Text;  
  37. using System.Runtime.InteropServices;  
  38.  
  39. namespace System.IO   
  40. {  
  41.     [Serializable]  
  42.     public class DynamicStreamReader : TextReader   
  43.     {  
  44.  
  45.         const int DefaultBufferSize = 1024;  
  46.         const int DefaultFileBufferSize = 4096;  
  47.         const int MinimumBufferSize = 128;  
  48.  
  49.         //  
  50.         // The input buffer  
  51.         //  
  52.         byte [] input_buffer;  
  53.  
  54.         //  
  55.         // The decoded buffer from the above input buffer  
  56.         //  
  57.         char [] decoded_buffer;  
  58.  
  59.         //  
  60.         // Decoded bytes in decoded_buffer.  
  61.         //  
  62.         int decoded_count;  
  63.  
  64.         //  
  65.         // Current position in the decoded_buffer  
  66.         //  
  67.         int pos;  
  68.  
  69.         //  
  70.         // Current position in the input_buffer  
  71.         //  
  72.         int pos_input;  
  73.  
  74.         //  
  75.         // The buffer size that we are using  
  76.         //  
  77.         int buffer_size;  
  78.  
  79.         int do_checks;  
  80.           
  81.         Encoding encoding;  
  82.         Decoder decoder;  
  83.  
  84.         Stream base_stream;  
  85.         bool mayBlock;  
  86.         StringBuilder line_builder;  
  87.  
  88.         private class NullStreamReader : DynamicStreamReader   
  89.         {  
  90.             public override int Peek ()  
  91.             {  
  92.                 return -1;  
  93.             }  
  94.  
  95.             public override int Read ()  
  96.             {  
  97.                 return -1;  
  98.             }  
  99.  
  100.             public override int Read ([InOutchar[] buffer, int indexint count)  
  101.             {  
  102.                 return 0;  
  103.             }  
  104.  
  105.             public override string ReadLine ()  
  106.             {  
  107.                 return null;  
  108.             }  
  109.  
  110.             public override string ReadToEnd ()  
  111.             {  
  112.                 return String.Empty;  
  113.             }  
  114.  
  115.             public override Stream BaseStream  
  116.             {  
  117.                 get { return Stream.Null; }  
  118.             }  
  119.  
  120.             public override Encoding CurrentEncoding  
  121.             {  
  122.                 get { return Encoding.Unicode; }  
  123.             }  
  124.         }  
  125.  
  126.         public new static readonly DynamicStreamReader Null =  (DynamicStreamReader)(new NullStreamReader());  
  127.           
  128.         internal DynamicStreamReader() {}  
  129.  
  130.         public DynamicStreamReader(Stream stream)  
  131.             : this (stream, Encoding.UTF8, true, DefaultBufferSize) { }  
  132.  
  133.         public DynamicStreamReader(Stream stream, bool detect_encoding_from_bytemarks)  
  134.             : this (stream, Encoding.UTF8, detect_encoding_from_bytemarks, DefaultBufferSize) { }  
  135.  
  136.         public DynamicStreamReader(Stream stream, Encoding encoding)  
  137.             : this (stream, encoding, true, DefaultBufferSize) { }  
  138.  
  139.         public DynamicStreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)  
  140.             : this (stream, encoding, detect_encoding_from_bytemarks, DefaultBufferSize) { }  
  141.           
  142.         public DynamicStreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)  
  143.         {  
  144.             Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);  
  145.         }  
  146.  
  147.         public DynamicStreamReader(string path)  
  148.             : this (path, Encoding.UTF8, true, DefaultFileBufferSize) { }  
  149.  
  150.         public DynamicStreamReader(string path, bool detect_encoding_from_bytemarks)  
  151.             : this (path, Encoding.UTF8, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }  
  152.  
  153.         public DynamicStreamReader(string path, Encoding encoding)  
  154.             : this (path, encoding, true, DefaultFileBufferSize) { }  
  155.  
  156.         public DynamicStreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks)  
  157.             : this (path, encoding, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }  
  158.           
  159.         public DynamicStreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)  
  160.         {  
  161.             if (null == path)  
  162.                 throw new ArgumentNullException("path");  
  163.             if (String.Empty == path)  
  164.                 throw new ArgumentException("Empty path not allowed");  
  165.             if (path.IndexOfAny (Path.InvalidPathChars) != -1)  
  166.                 throw new ArgumentException("path contains invalid characters");  
  167.             if (null == encoding)  
  168.                 throw new ArgumentNullException ("encoding");  
  169.             if (buffer_size <= 0)  
  170.                 throw new ArgumentOutOfRangeException ("buffer_size""The minimum size of the buffer must be positive");  
  171.  
  172.             string DirName = Path.GetDirectoryName(path);  
  173.             if (DirName != String.Empty && !Directory.Exists(DirName))  
  174.                 throw new DirectoryNotFoundException ("Directory '" + DirName + "' not found.");  
  175.             if (!File.Exists(path))  
  176.                 throw new FileNotFoundException("File not found.", path);  
  177.  
  178.             Stream stream = (Stream) File.OpenRead (path);  
  179.             Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);  
  180.         }  
  181.  
  182.         internal void Initialize (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)  
  183.         {  
  184.             if (null == stream)  
  185.                 throw new ArgumentNullException ("stream");  
  186.             if (null == encoding)  
  187.                 throw new ArgumentNullException ("encoding");  
  188.             if (!stream.CanRead)  
  189.                 throw new ArgumentException ("Cannot read stream");  
  190.             if (buffer_size <= 0)  
  191.                 throw new ArgumentOutOfRangeException ("buffer_size""The minimum size of the buffer must be positive");  
  192.  
  193.             if (buffer_size < MinimumBufferSize)  
  194.                 buffer_size = MinimumBufferSize;  
  195.  
  196.             base_stream = stream;  
  197.             input_buffer = new byte [buffer_size];  
  198.             this.buffer_size = buffer_size;  
  199.             this.encoding = encoding;  
  200.             decoder = encoding.GetDecoder ();  
  201.  
  202.             byte [] preamble = encoding.GetPreamble ();  
  203.             do_checks = detect_encoding_from_bytemarks ? 1 : 0;  
  204.             do_checks += (preamble.Length == 0) ? 0 : 2;  
  205.               
  206.             decoded_buffer = new char [encoding.GetMaxCharCount (buffer_size)];  
  207.             decoded_count = 0;  
  208.             pos = 0;  
  209.             pos_input =0;  
  210.         }  
  211.  
  212.         public virtual Stream BaseStream  
  213.         {  
  214.             get   
  215.             {  
  216.                 return base_stream;  
  217.             }  
  218.         }  
  219.  
  220.         public virtual Encoding CurrentEncoding  
  221.         {  
  222.             get   
  223.             {  
  224.                 if (encoding == null)  
  225.                     throw new Exception ();  
  226.                 return encoding;  
  227.             }  
  228.             set 
  229.             {  
  230.                 encoding=value;  
  231.                 decoder = encoding.GetDecoder();  
  232.                 decoded_count = pos + decoder.GetChars (input_buffer, pos_input, cbEncoded - pos_input, decoded_buffer, pos);  
  233.                 //DiscardBufferedData();  
  234.             }  
  235.         }  
  236.  
  237.         public override void Close ()  
  238.         {  
  239.             Dispose (true);  
  240.         }  
  241.  
  242.         protected override void Dispose (bool disposing)  
  243.         {  
  244.             if (disposing && base_stream != null)  
  245.                 base_stream.Close ();  
  246.               
  247.             input_buffer = null;  
  248.             decoded_buffer = null;  
  249.             encoding = null;  
  250.             decoder = null;  
  251.             base_stream = null;  
  252.             base.Dispose (disposing);  
  253.         }  
  254.  
  255.         //  
  256.         // Provides auto-detection of the encoding, as well as skipping over  
  257.         // byte marks at the beginning of a stream.  
  258.         //  
  259.         int DoChecks (int count)  
  260.         {  
  261.             if ((do_checks & 2) == 2)  
  262.             {  
  263.                 byte [] preamble = encoding.GetPreamble ();  
  264.                 int c = preamble.Length;  
  265.                 if (count >= c)  
  266.                 {  
  267.                     int i;  
  268.                       
  269.                     for (i = 0; i < c; i++)  
  270.                         if (input_buffer [i] != preamble [i])  
  271.                             break;  
  272.  
  273.                     if (i == c)  
  274.                         return i;  
  275.                 }  
  276.             }  
  277.  
  278.             if ((do_checks & 1) == 1)  
  279.             {  
  280.                 if (count < 2)  
  281.                     return 0;  
  282.  
  283.                 if (input_buffer [0] == 0xfe && input_buffer [1] == 0xff)  
  284.                 {  
  285.                     this.encoding = Encoding.BigEndianUnicode;  
  286.                     return 2;  
  287.                 }  
  288.  
  289.                 if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe)  
  290.                 {  
  291.                     this.encoding = Encoding.Unicode;  
  292.                     return 2;  
  293.                 }  
  294.  
  295.                 if (count < 3)  
  296.                     return 0;  
  297.  
  298.                 if (input_buffer [0] == 0xef && input_buffer [1] == 0xbb && input_buffer [2] == 0xbf)  
  299.                 {  
  300.                     this.encoding = Encoding.UTF8;  
  301.                     return 3;  
  302.                 }  
  303.             }  
  304.  
  305.             return 0;  
  306.         }  
  307.  
  308.         public void DiscardBufferedData ()  
  309.         {  
  310.             pos = decoded_count = 0;  
  311.             mayBlock = false;  
  312.             // Discard internal state of the decoder too.  
  313.             decoder = encoding.GetDecoder ();  
  314.         }  
  315.           
  316.         int cbEncoded;   
  317.         int parse_start;  
  318.         // the buffer is empty, fill it again  
  319.         private int ReadBuffer ()  
  320.         {  
  321.             pos = 0;  
  322.             pos_input = 0;  
  323.             cbEncoded = 0;  
  324.  
  325.             // keep looping until the decoder gives us some chars  
  326.             decoded_count = 0;  
  327.             parse_start = 0;  
  328.             do      
  329.             {  
  330.                 cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);  
  331.                   
  332.                 if (cbEncoded == 0)  
  333.                     return 0;  
  334.  
  335.                 mayBlock = (cbEncoded < buffer_size);  
  336.                 if (do_checks > 0)  
  337.                 {  
  338.                     Encoding old = encoding;  
  339.                     parse_start = DoChecks (cbEncoded);  
  340.                     if (old != encoding)  
  341.                     {  
  342.                         decoder = encoding.GetDecoder ();  
  343.                     }  
  344.                     do_checks = 0;  
  345.                     cbEncoded -= parse_start;  
  346.                 }  
  347.                 decoded_count += decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);  
  348.                 parse_start = 0;  
  349.             } while (decoded_count == 0);  
  350.  
  351.             return decoded_count;  
  352.         }  
  353.  
  354.         public override int Peek ()  
  355.         {  
  356.             if (base_stream == null)  
  357.                 throw new ObjectDisposedException ("StreamReader""Cannot read from a closed StreamReader");  
  358.             if (pos >= decoded_count && (mayBlock || ReadBuffer () == 0))  
  359.                 return -1;  
  360.  
  361.             return decoded_buffer [pos];  
  362.         }  
  363.  
  364.         public override int Read ()  
  365.         {  
  366.             throw new Exception("Dynamic Reader could not read!");  
  367.         }  
  368.  
  369.         public override int Read ([InOutchar[] dest_buffer, int indexint count)  
  370.         {  
  371.             throw new Exception("Dynamic Reader could not read!");  
  372.         }  
  373.  
  374.         bool foundCR_input;  
  375.         int FindNextInputEOL()  
  376.         {  
  377.             char c = '\0';  
  378.             for (; pos_input < cbEncoded; pos_input++)   
  379.             {  
  380.                 c = (char)input_buffer [pos_input];  
  381.                 if (c == '\n')   
  382.                 {  
  383.                     pos_input++;  
  384.                     int res = (foundCR_input) ? (pos_input - 2) : (pos_input - 1);  
  385.                     if (res < 0)  
  386.                         res = 0; // if a new buffer starts with a \n and there was a \r at 
  387.                     // the end of the previous one, we get here.  
  388.                     foundCR_input = false;  
  389.                     return res;  
  390.                 }   
  391.                 else if (foundCR_input)   
  392.                 {  
  393.                     foundCR_input = false;  
  394.                     return pos - 1;  
  395.                 }  
  396.  
  397.                 foundCR_input = (c == '\r');  
  398.             }  
  399.  
  400.             return -1;  
  401.         }  
  402.  
  403.         bool foundCR;  
  404.         int FindNextEOL ()  
  405.         {  
  406.             FindNextInputEOL();  
  407.             char c = '\0';  
  408.             for (; pos < decoded_count; pos++)   
  409.             {  
  410.                 c = decoded_buffer [pos];  
  411.                 if (c == '\n')   
  412.                 {  
  413.                     pos++;  
  414.                     int res = (foundCR) ? (pos - 2) : (pos - 1);  
  415.                     if (res < 0)  
  416.                         res = 0; // if a new buffer starts with a \n and there was a \r at 
  417.                     // the end of the previous one, we get here.  
  418.                     foundCR = false;  
  419.                     return res;  
  420.                 }   
  421.                 else if (foundCR)   
  422.                 {  
  423.                     foundCR = false;  
  424.                     return pos - 1;  
  425.                 }  
  426.  
  427.                 foundCR = (c == '\r');  
  428.             }  
  429.  
  430.             return -1;  
  431.         }  
  432.  
  433.         public override string ReadLine()  
  434.         {  
  435.             if (base_stream == null)  
  436.                 throw new ObjectDisposedException ("StreamReader""Cannot read from a closed StreamReader");  
  437.  
  438.             if (pos >= decoded_count && ReadBuffer () == 0)  
  439.                 return null;  
  440.  
  441.             int begin = pos;  
  442.             int end = FindNextEOL ();  
  443.             if (end < decoded_count && end >= begin)  
  444.                 return new string (decoded_buffer, beginend - begin);  
  445.  
  446.             if (line_builder == null)  
  447.                 line_builder = new StringBuilder ();  
  448.             else 
  449.                 line_builder.Length = 0;  
  450.  
  451.             while (true)   
  452.             {  
  453.                 if (foundCR) // don't include the trailing CR if present  
  454.                     decoded_count--;  
  455.  
  456.                 line_builder.Append (new string (decoded_buffer, begin, decoded_count - begin));  
  457.                 if (ReadBuffer () == 0)   
  458.                 {  
  459.                     if (line_builder.Capacity > 32768)   
  460.                     {  
  461.                         StringBuilder sb = line_builder;  
  462.                         line_builder = null;  
  463.                         return sb.ToString (0, sb.Length);  
  464.                     }  
  465.                     return line_builder.ToString (0, line_builder.Length);  
  466.                 }  
  467.  
  468.                 begin = pos;  
  469.                 end = FindNextEOL ();  
  470.                 if (end < decoded_count && end >= begin)   
  471.                 {  
  472.                     line_builder.Append (new string (decoded_buffer, beginend - begin));  
  473.                     if (line_builder.Capacity > 32768)   
  474.                     {  
  475.                         StringBuilder sb = line_builder;  
  476.                         line_builder = null;  
  477.                         return sb.ToString (0, sb.Length);  
  478.                     }  
  479.                     return line_builder.ToString (0, line_builder.Length);  
  480.                 }  
  481.             }  
  482.         }  
  483.  
  484.         public override string ReadToEnd()  
  485.         {  
  486.             if (base_stream == null)  
  487.                 throw new ObjectDisposedException ("StreamReader""Cannot read from a closed StreamReader");  
  488.  
  489.             StringBuilder text = new StringBuilder ();  
  490.  
  491.             int size = decoded_buffer.Length;  
  492.             char [] buffer = new char [size];  
  493.             int len;  
  494.               
  495.             while ((len = Read (buffer, 0, size)) > 0)  
  496.                 text.Append (buffer, 0, len);  
  497.  
  498.             return text.ToString ();  
  499.         }  
  500.     }  
  501. }