StreamReader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. public class StreamReader : TextReader {
  39. const int DefaultBufferSize = 1024;
  40. const int DefaultFileBufferSize = 4096;
  41. const int MinimumBufferSize = 128;
  42. //
  43. // The input buffer
  44. //
  45. byte [] input_buffer;
  46. //
  47. // The decoded buffer from the above input buffer
  48. //
  49. char [] decoded_buffer;
  50. //
  51. // Decoded bytes in decoded_buffer.
  52. //
  53. int decoded_count;
  54. //
  55. // Current position in the decoded_buffer
  56. //
  57. int pos;
  58. //
  59. // The buffer size that we are using
  60. //
  61. int buffer_size;
  62. int do_checks;
  63. Encoding encoding;
  64. Decoder decoder;
  65. Stream base_stream;
  66. bool mayBlock;
  67. private class NullStreamReader : StreamReader {
  68. public override int Peek ()
  69. {
  70. return -1;
  71. }
  72. public override int Read ()
  73. {
  74. return -1;
  75. }
  76. public override int Read ([In, Out] char[] buffer, int index, int count)
  77. {
  78. return 0;
  79. }
  80. public override string ReadLine ()
  81. {
  82. return null;
  83. }
  84. public override string ReadToEnd ()
  85. {
  86. return String.Empty;
  87. }
  88. public override Stream BaseStream
  89. {
  90. get { return Stream.Null; }
  91. }
  92. public override Encoding CurrentEncoding
  93. {
  94. get { return Encoding.Unicode; }
  95. }
  96. }
  97. public new static readonly StreamReader Null = (StreamReader)(new NullStreamReader());
  98. internal StreamReader() {}
  99. public StreamReader(Stream stream)
  100. : this (stream, Encoding.UTF8Unmarked, true, DefaultBufferSize) { }
  101. public StreamReader(Stream stream, bool detect_encoding_from_bytemarks)
  102. : this (stream, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultBufferSize) { }
  103. public StreamReader(Stream stream, Encoding encoding)
  104. : this (stream, encoding, true, DefaultBufferSize) { }
  105. public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
  106. : this (stream, encoding, detect_encoding_from_bytemarks, DefaultBufferSize) { }
  107. public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
  108. {
  109. Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);
  110. }
  111. public StreamReader(string path)
  112. : this (path, Encoding.UTF8Unmarked, true, DefaultFileBufferSize) { }
  113. public StreamReader(string path, bool detect_encoding_from_bytemarks)
  114. : this (path, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
  115. public StreamReader(string path, Encoding encoding)
  116. : this (path, encoding, true, DefaultFileBufferSize) { }
  117. public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks)
  118. : this (path, encoding, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
  119. public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
  120. {
  121. if (null == path)
  122. throw new ArgumentNullException("path");
  123. if (String.Empty == path)
  124. throw new ArgumentException("Empty path not allowed");
  125. if (path.IndexOfAny (Path.InvalidPathChars) != -1)
  126. throw new ArgumentException("path contains invalid characters");
  127. if (null == encoding)
  128. throw new ArgumentNullException ("encoding");
  129. if (buffer_size <= 0)
  130. throw new ArgumentOutOfRangeException ("buffer_size", "The minimum size of the buffer must be positive");
  131. string DirName = Path.GetDirectoryName(path);
  132. if (DirName != String.Empty && !Directory.Exists(DirName))
  133. throw new DirectoryNotFoundException ("Directory '" + DirName + "' not found.");
  134. if (!File.Exists(path))
  135. throw new FileNotFoundException("File not found.", path);
  136. Stream stream = (Stream) File.OpenRead (path);
  137. Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);
  138. }
  139. internal void Initialize (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
  140. {
  141. if (null == stream)
  142. throw new ArgumentNullException ("stream");
  143. if (null == encoding)
  144. throw new ArgumentNullException ("encoding");
  145. if (!stream.CanRead)
  146. throw new ArgumentException ("Cannot read stream");
  147. if (buffer_size <= 0)
  148. throw new ArgumentOutOfRangeException ("buffer_size", "The minimum size of the buffer must be positive");
  149. if (buffer_size < MinimumBufferSize)
  150. buffer_size = MinimumBufferSize;
  151. base_stream = stream;
  152. input_buffer = new byte [buffer_size];
  153. this.buffer_size = buffer_size;
  154. this.encoding = encoding;
  155. decoder = encoding.GetDecoder ();
  156. byte [] preamble = encoding.GetPreamble ();
  157. do_checks = detect_encoding_from_bytemarks ? 1 : 0;
  158. do_checks += (preamble.Length == 0) ? 0 : 2;
  159. decoded_buffer = new char [encoding.GetMaxCharCount (buffer_size)];
  160. decoded_count = 0;
  161. pos = 0;
  162. }
  163. public virtual Stream BaseStream
  164. {
  165. get {
  166. return base_stream;
  167. }
  168. }
  169. public virtual Encoding CurrentEncoding
  170. {
  171. get {
  172. if (encoding == null)
  173. throw new Exception ();
  174. return encoding;
  175. }
  176. }
  177. public override void Close ()
  178. {
  179. Dispose (true);
  180. }
  181. protected override void Dispose (bool disposing)
  182. {
  183. if (disposing && base_stream != null)
  184. base_stream.Close ();
  185. input_buffer = null;
  186. decoded_buffer = null;
  187. encoding = null;
  188. decoder = null;
  189. base_stream = null;
  190. base.Dispose (disposing);
  191. }
  192. //
  193. // Provides auto-detection of the encoding, as well as skipping over
  194. // byte marks at the beginning of a stream.
  195. //
  196. int DoChecks (int count)
  197. {
  198. if ((do_checks & 2) == 2){
  199. byte [] preamble = encoding.GetPreamble ();
  200. int c = preamble.Length;
  201. if (count >= c){
  202. int i;
  203. for (i = 0; i < c; i++)
  204. if (input_buffer [i] != preamble [i])
  205. break;
  206. if (i == c)
  207. return i;
  208. }
  209. }
  210. if ((do_checks & 1) == 1){
  211. if (count < 2)
  212. return 0;
  213. if (input_buffer [0] == 0xfe && input_buffer [1] == 0xff){
  214. this.encoding = Encoding.BigEndianUnicode;
  215. return 2;
  216. }
  217. if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe){
  218. this.encoding = Encoding.Unicode;
  219. return 2;
  220. }
  221. if (count < 3)
  222. return 0;
  223. if (input_buffer [0] == 0xef && input_buffer [1] == 0xbb && input_buffer [2] == 0xbf){
  224. this.encoding = Encoding.UTF8Unmarked;
  225. return 3;
  226. }
  227. }
  228. return 0;
  229. }
  230. public void DiscardBufferedData ()
  231. {
  232. pos = decoded_count = 0;
  233. }
  234. // the buffer is empty, fill it again
  235. private int ReadBuffer ()
  236. {
  237. pos = 0;
  238. int cbEncoded = 0;
  239. // keep looping until the decoder gives us some chars
  240. decoded_count = 0;
  241. int parse_start = 0;
  242. do
  243. {
  244. cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);
  245. if (cbEncoded == 0)
  246. return 0;
  247. mayBlock = (cbEncoded < buffer_size);
  248. if (do_checks > 0){
  249. Encoding old = encoding;
  250. parse_start = DoChecks (cbEncoded);
  251. if (old != encoding){
  252. decoder = encoding.GetDecoder ();
  253. }
  254. do_checks = 0;
  255. cbEncoded -= parse_start;
  256. }
  257. decoded_count += decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
  258. parse_start = 0;
  259. } while (decoded_count == 0);
  260. return decoded_count;
  261. }
  262. public override int Peek ()
  263. {
  264. if (base_stream == null)
  265. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  266. if (pos >= decoded_count && (mayBlock || ReadBuffer () == 0))
  267. return -1;
  268. return decoded_buffer [pos];
  269. }
  270. public override int Read ()
  271. {
  272. if (base_stream == null)
  273. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  274. if (pos >= decoded_count && ReadBuffer () == 0)
  275. return -1;
  276. return decoded_buffer [pos++];
  277. }
  278. public override int Read ([In, Out] char[] dest_buffer, int index, int count)
  279. {
  280. if (base_stream == null)
  281. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  282. if (dest_buffer == null)
  283. throw new ArgumentNullException ("dest_buffer");
  284. if (index < 0)
  285. throw new ArgumentOutOfRangeException ("index", "< 0");
  286. if (count < 0)
  287. throw new ArgumentOutOfRangeException ("count", "< 0");
  288. // re-ordered to avoid possible integer overflow
  289. if (index > dest_buffer.Length - count)
  290. throw new ArgumentException ("index + count > dest_buffer.Length");
  291. int chars_read = 0;
  292. while (count > 0)
  293. {
  294. if (pos >= decoded_count && ReadBuffer () == 0)
  295. return chars_read > 0 ? chars_read : 0;
  296. int cch = Math.Min (decoded_count - pos, count);
  297. Array.Copy (decoded_buffer, pos, dest_buffer, index, cch);
  298. pos += cch;
  299. index += cch;
  300. count -= cch;
  301. chars_read += cch;
  302. }
  303. return chars_read;
  304. }
  305. public override string ReadLine()
  306. {
  307. if (base_stream == null)
  308. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  309. bool foundCR = false;
  310. StringBuilder text = new StringBuilder ();
  311. while (true) {
  312. int c = Read ();
  313. if (c == -1) { // end of stream
  314. if (text.Length == 0)
  315. return null;
  316. if (foundCR)
  317. text.Length--;
  318. break;
  319. }
  320. if (c == '\n') { // newline
  321. if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
  322. text.Length--;
  323. foundCR = false;
  324. break;
  325. } else if (foundCR) {
  326. pos--;
  327. text.Length--;
  328. break;
  329. }
  330. if (c == '\r')
  331. foundCR = true;
  332. text.Append ((char) c);
  333. }
  334. return text.ToString ();
  335. }
  336. public override string ReadToEnd()
  337. {
  338. if (base_stream == null)
  339. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  340. StringBuilder text = new StringBuilder ();
  341. int size = decoded_buffer.Length;
  342. char [] buffer = new char [size];
  343. int len;
  344. while ((len = Read (buffer, 0, size)) != 0)
  345. text.Append (buffer, 0, len);
  346. return text.ToString ();
  347. }
  348. }
  349. }