2 // System.IO.StreamReader.cs
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Miguel de Icaza (miguel@ximian.com)
8 // (C) Ximian, Inc. http://www.ximian.com
9 // Copyright (C) 2004 Novell (http://www.novell.com)
13 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
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 FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 using System.Runtime.InteropServices;
41 public class StreamReader : TextReader {
43 const int DefaultBufferSize = 1024;
44 const int DefaultFileBufferSize = 4096;
45 const int MinimumBufferSize = 128;
53 // The decoded buffer from the above input buffer
55 char [] decoded_buffer;
58 // Decoded bytes in decoded_buffer.
63 // Current position in the decoded_buffer
68 // The buffer size that we are using
79 StringBuilder line_builder;
81 private class NullStreamReader : StreamReader {
82 public override int Peek ()
87 public override int Read ()
92 public override int Read ([In, Out] char[] buffer, int index, int count)
97 public override string ReadLine ()
102 public override string ReadToEnd ()
107 public override Stream BaseStream
109 get { return Stream.Null; }
112 public override Encoding CurrentEncoding
114 get { return Encoding.Unicode; }
118 public new static readonly StreamReader Null = (StreamReader)(new NullStreamReader());
120 internal StreamReader() {}
122 public StreamReader(Stream stream)
123 : this (stream, Encoding.UTF8Unmarked, true, DefaultBufferSize) { }
125 public StreamReader(Stream stream, bool detect_encoding_from_bytemarks)
126 : this (stream, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultBufferSize) { }
128 public StreamReader(Stream stream, Encoding encoding)
129 : this (stream, encoding, true, DefaultBufferSize) { }
131 public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
132 : this (stream, encoding, detect_encoding_from_bytemarks, DefaultBufferSize) { }
134 public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
136 Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);
139 public StreamReader(string path)
140 : this (path, Encoding.UTF8Unmarked, true, DefaultFileBufferSize) { }
142 public StreamReader(string path, bool detect_encoding_from_bytemarks)
143 : this (path, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
145 public StreamReader(string path, Encoding encoding)
146 : this (path, encoding, true, DefaultFileBufferSize) { }
148 public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks)
149 : this (path, encoding, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
151 public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
154 throw new ArgumentNullException("path");
155 if (String.Empty == path)
156 throw new ArgumentException("Empty path not allowed");
157 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
158 throw new ArgumentException("path contains invalid characters");
159 if (null == encoding)
160 throw new ArgumentNullException ("encoding");
161 if (buffer_size <= 0)
162 throw new ArgumentOutOfRangeException ("buffer_size", "The minimum size of the buffer must be positive");
164 string DirName = Path.GetDirectoryName(path);
165 if (DirName != String.Empty && !Directory.Exists(DirName))
166 throw new DirectoryNotFoundException ("Directory '" + DirName + "' not found.");
167 if (!File.Exists(path))
168 throw new FileNotFoundException("File not found.", path);
170 Stream stream = (Stream) File.OpenRead (path);
171 Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);
174 internal void Initialize (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
177 throw new ArgumentNullException ("stream");
178 if (null == encoding)
179 throw new ArgumentNullException ("encoding");
181 throw new ArgumentException ("Cannot read stream");
182 if (buffer_size <= 0)
183 throw new ArgumentOutOfRangeException ("buffer_size", "The minimum size of the buffer must be positive");
185 if (buffer_size < MinimumBufferSize)
186 buffer_size = MinimumBufferSize;
188 base_stream = stream;
189 input_buffer = new byte [buffer_size];
190 this.buffer_size = buffer_size;
191 this.encoding = encoding;
192 decoder = encoding.GetDecoder ();
194 byte [] preamble = encoding.GetPreamble ();
195 do_checks = detect_encoding_from_bytemarks ? 1 : 0;
196 do_checks += (preamble.Length == 0) ? 0 : 2;
198 decoded_buffer = new char [encoding.GetMaxCharCount (buffer_size)];
203 public virtual Stream BaseStream
210 public virtual Encoding CurrentEncoding
213 if (encoding == null)
214 throw new Exception ();
219 public override void Close ()
224 protected override void Dispose (bool disposing)
226 if (disposing && base_stream != null)
227 base_stream.Close ();
230 decoded_buffer = null;
234 base.Dispose (disposing);
238 // Provides auto-detection of the encoding, as well as skipping over
239 // byte marks at the beginning of a stream.
241 int DoChecks (int count)
243 if ((do_checks & 2) == 2){
244 byte [] preamble = encoding.GetPreamble ();
245 int c = preamble.Length;
249 for (i = 0; i < c; i++)
250 if (input_buffer [i] != preamble [i])
258 if ((do_checks & 1) == 1){
262 if (input_buffer [0] == 0xfe && input_buffer [1] == 0xff){
263 this.encoding = Encoding.BigEndianUnicode;
267 if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe){
268 this.encoding = Encoding.Unicode;
275 if (input_buffer [0] == 0xef && input_buffer [1] == 0xbb && input_buffer [2] == 0xbf){
276 this.encoding = Encoding.UTF8Unmarked;
284 public void DiscardBufferedData ()
286 pos = decoded_count = 0;
288 // Discard internal state of the decoder too.
289 decoder = encoding.GetDecoder ();
292 // the buffer is empty, fill it again
293 private int ReadBuffer ()
298 // keep looping until the decoder gives us some chars
303 cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);
308 mayBlock = (cbEncoded < buffer_size);
310 Encoding old = encoding;
311 parse_start = DoChecks (cbEncoded);
312 if (old != encoding){
313 decoder = encoding.GetDecoder ();
316 cbEncoded -= parse_start;
319 decoded_count += decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
321 } while (decoded_count == 0);
323 return decoded_count;
326 public override int Peek ()
328 if (base_stream == null)
329 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
330 if (pos >= decoded_count && (mayBlock || ReadBuffer () == 0))
333 return decoded_buffer [pos];
336 public override int Read ()
338 if (base_stream == null)
339 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
340 if (pos >= decoded_count && ReadBuffer () == 0)
343 return decoded_buffer [pos++];
346 public override int Read ([In, Out] char[] dest_buffer, int index, int count)
348 if (base_stream == null)
349 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
350 if (dest_buffer == null)
351 throw new ArgumentNullException ("dest_buffer");
353 throw new ArgumentOutOfRangeException ("index", "< 0");
355 throw new ArgumentOutOfRangeException ("count", "< 0");
356 // re-ordered to avoid possible integer overflow
357 if (index > dest_buffer.Length - count)
358 throw new ArgumentException ("index + count > dest_buffer.Length");
363 if (pos >= decoded_count && ReadBuffer () == 0)
364 return chars_read > 0 ? chars_read : 0;
366 int cch = Math.Min (decoded_count - pos, count);
367 Array.Copy (decoded_buffer, pos, dest_buffer, index, cch);
380 for (; pos < decoded_count; pos++) {
381 c = decoded_buffer [pos];
384 int res = (foundCR) ? (pos - 2) : (pos - 1);
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.
390 } else if (foundCR) {
395 foundCR = (c == '\r');
401 public override string ReadLine()
403 if (base_stream == null)
404 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
406 if (pos >= decoded_count && ReadBuffer () == 0)
410 int end = FindNextEOL ();
411 if (end < decoded_count && end >= begin)
412 return new string (decoded_buffer, begin, end - begin);
414 if (line_builder == null)
415 line_builder = new StringBuilder ();
417 line_builder.Length = 0;
420 if (foundCR) // don't include the trailing CR if present
423 line_builder.Append (new string (decoded_buffer, begin, decoded_count - begin));
424 if (ReadBuffer () == 0) {
425 if (line_builder.Capacity > 32768) {
426 StringBuilder sb = line_builder;
428 return sb.ToString (0, sb.Length);
430 return line_builder.ToString (0, line_builder.Length);
434 end = FindNextEOL ();
435 if (end < decoded_count && end >= begin) {
436 line_builder.Append (new string (decoded_buffer, begin, end - begin));
437 if (line_builder.Capacity > 32768) {
438 StringBuilder sb = line_builder;
440 return sb.ToString (0, sb.Length);
442 return line_builder.ToString (0, line_builder.Length);
447 public override string ReadToEnd()
449 if (base_stream == null)
450 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
452 StringBuilder text = new StringBuilder ();
454 int size = decoded_buffer.Length;
455 char [] buffer = new char [size];
458 while ((len = Read (buffer, 0, size)) != 0)
459 text.Append (buffer, 0, len);
461 return text.ToString ();