StreamReader.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. [ComVisible (true)]
  39. public class StreamReader : TextReader {
  40. const int DefaultBufferSize = 1024;
  41. const int DefaultFileBufferSize = 4096;
  42. const int MinimumBufferSize = 128;
  43. //
  44. // The input buffer
  45. //
  46. byte [] input_buffer;
  47. //
  48. // The decoded buffer from the above input buffer
  49. //
  50. char [] decoded_buffer;
  51. //
  52. // Decoded bytes in decoded_buffer.
  53. //
  54. int decoded_count;
  55. //
  56. // Current position in the decoded_buffer
  57. //
  58. int pos;
  59. //
  60. // The buffer size that we are using
  61. //
  62. int buffer_size;
  63. int do_checks;
  64. Encoding encoding;
  65. Decoder decoder;
  66. Stream base_stream;
  67. bool mayBlock;
  68. StringBuilder line_builder;
  69. private class NullStreamReader : StreamReader {
  70. public override int Peek ()
  71. {
  72. return -1;
  73. }
  74. public override int Read ()
  75. {
  76. return -1;
  77. }
  78. public override int Read ([In, Out] char[] buffer, int index, int count)
  79. {
  80. return 0;
  81. }
  82. public override string ReadLine ()
  83. {
  84. return null;
  85. }
  86. public override string ReadToEnd ()
  87. {
  88. return String.Empty;
  89. }
  90. public override Stream BaseStream
  91. {
  92. get { return Stream.Null; }
  93. }
  94. public override Encoding CurrentEncoding
  95. {
  96. get { return Encoding.Unicode; }
  97. }
  98. }
  99. public new static readonly StreamReader Null = (StreamReader)(new NullStreamReader());
  100. internal StreamReader() {}
  101. public StreamReader(Stream stream)
  102. : this (stream, Encoding.UTF8Unmarked, true, DefaultBufferSize) { }
  103. public StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks)
  104. : this (stream, Encoding.UTF8Unmarked, detectEncodingFromByteOrderMarks, DefaultBufferSize) { }
  105. public StreamReader(Stream stream, Encoding encoding)
  106. : this (stream, encoding, true, DefaultBufferSize) { }
  107. public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
  108. : this (stream, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize) { }
  109. public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  110. {
  111. Initialize (stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
  112. }
  113. public StreamReader(string path)
  114. : this (path, Encoding.UTF8Unmarked, true, DefaultFileBufferSize) { }
  115. public StreamReader(string path, bool detectEncodingFromByteOrderMarks)
  116. : this (path, Encoding.UTF8Unmarked, detectEncodingFromByteOrderMarks, DefaultFileBufferSize) { }
  117. public StreamReader(string path, Encoding encoding)
  118. : this (path, encoding, true, DefaultFileBufferSize) { }
  119. public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
  120. : this (path, encoding, detectEncodingFromByteOrderMarks, DefaultFileBufferSize) { }
  121. public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  122. {
  123. if (null == path)
  124. throw new ArgumentNullException("path");
  125. if (String.Empty == path)
  126. throw new ArgumentException("Empty path not allowed");
  127. if (path.IndexOfAny (Path.InvalidPathChars) != -1)
  128. throw new ArgumentException("path contains invalid characters");
  129. if (null == encoding)
  130. throw new ArgumentNullException ("encoding");
  131. if (bufferSize <= 0)
  132. throw new ArgumentOutOfRangeException ("bufferSize", "The minimum size of the buffer must be positive");
  133. Stream stream = (Stream) File.OpenRead (path);
  134. Initialize (stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
  135. }
  136. internal void Initialize (Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  137. {
  138. if (null == stream)
  139. throw new ArgumentNullException ("stream");
  140. if (null == encoding)
  141. throw new ArgumentNullException ("encoding");
  142. if (!stream.CanRead)
  143. throw new ArgumentException ("Cannot read stream");
  144. if (bufferSize <= 0)
  145. throw new ArgumentOutOfRangeException ("bufferSize", "The minimum size of the buffer must be positive");
  146. if (bufferSize < MinimumBufferSize)
  147. bufferSize = MinimumBufferSize;
  148. base_stream = stream;
  149. input_buffer = new byte [bufferSize];
  150. this.buffer_size = bufferSize;
  151. this.encoding = encoding;
  152. decoder = encoding.GetDecoder ();
  153. byte [] preamble = encoding.GetPreamble ();
  154. do_checks = detectEncodingFromByteOrderMarks ? 1 : 0;
  155. do_checks += (preamble.Length == 0) ? 0 : 2;
  156. // since GetChars() might add flushed character, it
  157. // should have additional char buffer for extra 1
  158. // (probably 1 is ok, but might be insufficient. I'm not sure)
  159. decoded_buffer = new char [encoding.GetMaxCharCount (bufferSize) + 1];
  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 bool EndOfStream {
  178. get { return Peek () < 0; }
  179. }
  180. public override void Close ()
  181. {
  182. Dispose (true);
  183. }
  184. protected override void Dispose (bool disposing)
  185. {
  186. if (disposing && base_stream != null)
  187. base_stream.Close ();
  188. input_buffer = null;
  189. decoded_buffer = null;
  190. encoding = null;
  191. decoder = null;
  192. base_stream = null;
  193. base.Dispose (disposing);
  194. }
  195. //
  196. // Provides auto-detection of the encoding, as well as skipping over
  197. // byte marks at the beginning of a stream.
  198. //
  199. int DoChecks (int count)
  200. {
  201. if ((do_checks & 2) == 2){
  202. byte [] preamble = encoding.GetPreamble ();
  203. int c = preamble.Length;
  204. if (count >= c){
  205. int i;
  206. for (i = 0; i < c; i++)
  207. if (input_buffer [i] != preamble [i])
  208. break;
  209. if (i == c)
  210. return i;
  211. }
  212. }
  213. if ((do_checks & 1) == 1){
  214. if (count < 2)
  215. return 0;
  216. if (input_buffer [0] == 0xfe && input_buffer [1] == 0xff){
  217. this.encoding = Encoding.BigEndianUnicode;
  218. return 2;
  219. }
  220. if (count < 3)
  221. return 0;
  222. if (input_buffer [0] == 0xef && input_buffer [1] == 0xbb && input_buffer [2] == 0xbf){
  223. this.encoding = Encoding.UTF8Unmarked;
  224. return 3;
  225. }
  226. if (count < 4) {
  227. if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe && input_buffer [2] != 0) {
  228. this.encoding = Encoding.Unicode;
  229. return 2;
  230. }
  231. return 0;
  232. }
  233. if (input_buffer [0] == 0 && input_buffer [1] == 0
  234. && input_buffer [2] == 0xfe && input_buffer [3] == 0xff)
  235. {
  236. this.encoding = Encoding.BigEndianUTF32;
  237. return 4;
  238. }
  239. if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe) {
  240. if (input_buffer [2] == 0 && input_buffer[3] == 0) {
  241. this.encoding = Encoding.UTF32;
  242. return 4;
  243. }
  244. this.encoding = Encoding.Unicode;
  245. return 2;
  246. }
  247. }
  248. return 0;
  249. }
  250. public void DiscardBufferedData ()
  251. {
  252. pos = decoded_count = 0;
  253. mayBlock = false;
  254. // Discard internal state of the decoder too.
  255. decoder = encoding.GetDecoder ();
  256. }
  257. // the buffer is empty, fill it again
  258. private int ReadBuffer ()
  259. {
  260. pos = 0;
  261. int cbEncoded = 0;
  262. // keep looping until the decoder gives us some chars
  263. decoded_count = 0;
  264. int parse_start = 0;
  265. do
  266. {
  267. cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);
  268. if (cbEncoded <= 0)
  269. return 0;
  270. mayBlock = (cbEncoded < buffer_size);
  271. if (do_checks > 0){
  272. Encoding old = encoding;
  273. parse_start = DoChecks (cbEncoded);
  274. if (old != encoding){
  275. decoder = encoding.GetDecoder ();
  276. }
  277. do_checks = 0;
  278. cbEncoded -= parse_start;
  279. }
  280. decoded_count += decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
  281. parse_start = 0;
  282. } while (decoded_count == 0);
  283. return decoded_count;
  284. }
  285. //
  286. // Peek can block:
  287. // http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=96484
  288. //
  289. public override int Peek ()
  290. {
  291. if (base_stream == null)
  292. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  293. if (pos >= decoded_count && ReadBuffer () == 0)
  294. return -1;
  295. return decoded_buffer [pos];
  296. }
  297. //
  298. // Used internally by our console, as it previously depended on Peek() being a
  299. // routine that would not block.
  300. //
  301. internal bool DataAvailable ()
  302. {
  303. return pos < decoded_count;
  304. }
  305. public override int Read ()
  306. {
  307. if (base_stream == null)
  308. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  309. if (pos >= decoded_count && ReadBuffer () == 0)
  310. return -1;
  311. return decoded_buffer [pos++];
  312. }
  313. public override int Read ([In, Out] char[] buffer, int index, int count)
  314. {
  315. if (base_stream == null)
  316. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  317. if (buffer == null)
  318. throw new ArgumentNullException ("buffer");
  319. if (index < 0)
  320. throw new ArgumentOutOfRangeException ("index", "< 0");
  321. if (count < 0)
  322. throw new ArgumentOutOfRangeException ("count", "< 0");
  323. // re-ordered to avoid possible integer overflow
  324. if (index > buffer.Length - count)
  325. throw new ArgumentException ("index + count > buffer.Length");
  326. int chars_read = 0;
  327. while (count > 0)
  328. {
  329. if (pos >= decoded_count && ReadBuffer () == 0)
  330. return chars_read > 0 ? chars_read : 0;
  331. int cch = Math.Min (decoded_count - pos, count);
  332. Array.Copy (decoded_buffer, pos, buffer, index, cch);
  333. pos += cch;
  334. index += cch;
  335. count -= cch;
  336. chars_read += cch;
  337. if (mayBlock)
  338. break;
  339. }
  340. return chars_read;
  341. }
  342. bool foundCR;
  343. int FindNextEOL ()
  344. {
  345. char c = '\0';
  346. for (; pos < decoded_count; pos++) {
  347. c = decoded_buffer [pos];
  348. if (c == '\n') {
  349. pos++;
  350. int res = (foundCR) ? (pos - 2) : (pos - 1);
  351. if (res < 0)
  352. res = 0; // if a new buffer starts with a \n and there was a \r at
  353. // the end of the previous one, we get here.
  354. foundCR = false;
  355. return res;
  356. } else if (foundCR) {
  357. foundCR = false;
  358. if (pos == 0)
  359. return -2; // Need to flush the current buffered line.
  360. // This is a \r at the end of the previous decoded buffer that
  361. // is not followed by a \n in the current decoded buffer.
  362. return pos - 1;
  363. }
  364. foundCR = (c == '\r');
  365. }
  366. return -1;
  367. }
  368. public override string ReadLine()
  369. {
  370. if (base_stream == null)
  371. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  372. if (pos >= decoded_count && ReadBuffer () == 0)
  373. return null;
  374. int begin = pos;
  375. int end = FindNextEOL ();
  376. if (end < decoded_count && end >= begin)
  377. return new string (decoded_buffer, begin, end - begin);
  378. else if (end == -2)
  379. return line_builder.ToString (0, line_builder.Length);
  380. if (line_builder == null)
  381. line_builder = new StringBuilder ();
  382. else
  383. line_builder.Length = 0;
  384. while (true) {
  385. if (foundCR) // don't include the trailing CR if present
  386. decoded_count--;
  387. line_builder.Append (decoded_buffer, begin, decoded_count - begin);
  388. if (ReadBuffer () == 0) {
  389. if (line_builder.Capacity > 32768) {
  390. StringBuilder sb = line_builder;
  391. line_builder = null;
  392. return sb.ToString (0, sb.Length);
  393. }
  394. return line_builder.ToString (0, line_builder.Length);
  395. }
  396. begin = pos;
  397. end = FindNextEOL ();
  398. if (end < decoded_count && end >= begin) {
  399. line_builder.Append (decoded_buffer, begin, end - begin);
  400. if (line_builder.Capacity > 32768) {
  401. StringBuilder sb = line_builder;
  402. line_builder = null;
  403. return sb.ToString (0, sb.Length);
  404. }
  405. return line_builder.ToString (0, line_builder.Length);
  406. } else if (end == -2)
  407. return line_builder.ToString (0, line_builder.Length);
  408. }
  409. }
  410. public override string ReadToEnd()
  411. {
  412. if (base_stream == null)
  413. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  414. StringBuilder text = new StringBuilder ();
  415. int size = decoded_buffer.Length;
  416. char [] buffer = new char [size];
  417. int len;
  418. while ((len = Read (buffer, 0, size)) > 0)
  419. text.Append (buffer, 0, len);
  420. return text.ToString ();
  421. }
  422. }
  423. }