StreamReader.cs 13 KB

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