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
80 private class NullStreamReader : StreamReader {
81 public override int Peek ()
86 public override int Read ()
91 public override int Read ([In, Out] char[] buffer, int index, int count)
96 public override string ReadLine ()
101 public override string ReadToEnd ()
106 public override Stream BaseStream
108 get { return Stream.Null; }
111 public override Encoding CurrentEncoding
113 get { return Encoding.Unicode; }
117 public new static readonly StreamReader Null = (StreamReader)(new NullStreamReader());
119 internal StreamReader() {}
121 public StreamReader(Stream stream)
122 : this (stream, Encoding.UTF8Unmarked, true, DefaultBufferSize) { }
124 public StreamReader(Stream stream, bool detect_encoding_from_bytemarks)
125 : this (stream, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultBufferSize) { }
127 public StreamReader(Stream stream, Encoding encoding)
128 : this (stream, encoding, true, DefaultBufferSize) { }
130 public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
131 : this (stream, encoding, detect_encoding_from_bytemarks, DefaultBufferSize) { }
133 public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
135 Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);
138 public StreamReader(string path)
139 : this (path, Encoding.UTF8Unmarked, true, DefaultFileBufferSize) { }
141 public StreamReader(string path, bool detect_encoding_from_bytemarks)
142 : this (path, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
144 public StreamReader(string path, Encoding encoding)
145 : this (path, encoding, true, DefaultFileBufferSize) { }
147 public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks)
148 : this (path, encoding, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
150 public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
153 throw new ArgumentNullException("path");
154 if (String.Empty == path)
155 throw new ArgumentException("Empty path not allowed");
156 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
157 throw new ArgumentException("path contains invalid characters");
158 if (null == encoding)
159 throw new ArgumentNullException ("encoding");
160 if (buffer_size <= 0)
161 throw new ArgumentOutOfRangeException ("buffer_size", "The minimum size of the buffer must be positive");
163 string DirName = Path.GetDirectoryName(path);
164 if (DirName != String.Empty && !Directory.Exists(DirName))
165 throw new DirectoryNotFoundException ("Directory '" + DirName + "' not found.");
166 if (!File.Exists(path))
167 throw new FileNotFoundException("File not found.", path);
169 Stream stream = (Stream) File.OpenRead (path);
170 Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);
173 internal void Initialize (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
176 throw new ArgumentNullException ("stream");
177 if (null == encoding)
178 throw new ArgumentNullException ("encoding");
180 throw new ArgumentException ("Cannot read stream");
181 if (buffer_size <= 0)
182 throw new ArgumentOutOfRangeException ("buffer_size", "The minimum size of the buffer must be positive");
184 if (buffer_size < MinimumBufferSize)
185 buffer_size = MinimumBufferSize;
187 base_stream = stream;
188 input_buffer = new byte [buffer_size];
189 this.buffer_size = buffer_size;
190 this.encoding = encoding;
191 decoder = encoding.GetDecoder ();
193 byte [] preamble = encoding.GetPreamble ();
194 do_checks = detect_encoding_from_bytemarks ? 1 : 0;
195 do_checks += (preamble.Length == 0) ? 0 : 2;
197 decoded_buffer = new char [encoding.GetMaxCharCount (buffer_size)];
202 public virtual Stream BaseStream
209 public virtual Encoding CurrentEncoding
212 if (encoding == null)
213 throw new Exception ();
218 public override void Close ()
223 protected override void Dispose (bool disposing)
225 if (disposing && base_stream != null)
226 base_stream.Close ();
229 decoded_buffer = null;
233 base.Dispose (disposing);
237 // Provides auto-detection of the encoding, as well as skipping over
238 // byte marks at the beginning of a stream.
240 int DoChecks (int count)
242 if ((do_checks & 2) == 2){
243 byte [] preamble = encoding.GetPreamble ();
244 int c = preamble.Length;
248 for (i = 0; i < c; i++)
249 if (input_buffer [i] != preamble [i])
257 if ((do_checks & 1) == 1){
261 if (input_buffer [0] == 0xfe && input_buffer [1] == 0xff){
262 this.encoding = Encoding.BigEndianUnicode;
266 if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe){
267 this.encoding = Encoding.Unicode;
274 if (input_buffer [0] == 0xef && input_buffer [1] == 0xbb && input_buffer [2] == 0xbf){
275 this.encoding = Encoding.UTF8Unmarked;
283 public void DiscardBufferedData ()
285 pos = decoded_count = 0;
289 // the buffer is empty, fill it again
290 private int ReadBuffer ()
295 // keep looping until the decoder gives us some chars
300 cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);
305 mayBlock = (cbEncoded < buffer_size);
307 Encoding old = encoding;
308 parse_start = DoChecks (cbEncoded);
309 if (old != encoding){
310 decoder = encoding.GetDecoder ();
313 cbEncoded -= parse_start;
316 decoded_count += decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
318 } while (decoded_count == 0);
320 return decoded_count;
323 public override int Peek ()
325 if (base_stream == null)
326 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
327 if (pos >= decoded_count && (mayBlock || ReadBuffer () == 0))
330 return decoded_buffer [pos];
333 public override int Read ()
335 if (base_stream == null)
336 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
337 if (pos >= decoded_count && ReadBuffer () == 0)
340 return decoded_buffer [pos++];
343 public override int Read ([In, Out] char[] dest_buffer, int index, int count)
345 if (base_stream == null)
346 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
347 if (dest_buffer == null)
348 throw new ArgumentNullException ("dest_buffer");
350 throw new ArgumentOutOfRangeException ("index", "< 0");
352 throw new ArgumentOutOfRangeException ("count", "< 0");
353 // re-ordered to avoid possible integer overflow
354 if (index > dest_buffer.Length - count)
355 throw new ArgumentException ("index + count > dest_buffer.Length");
360 if (pos >= decoded_count && ReadBuffer () == 0)
361 return chars_read > 0 ? chars_read : 0;
363 int cch = Math.Min (decoded_count - pos, count);
364 Array.Copy (decoded_buffer, pos, dest_buffer, index, cch);
373 public override string ReadLine()
375 if (base_stream == null)
376 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
378 bool foundCR = false;
379 StringBuilder text = new StringBuilder ();
384 if (c == -1) { // end of stream
385 if (text.Length == 0)
394 if (c == '\n') { // newline
395 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
400 } else if (foundCR) {
410 text.Append ((char) c);
413 return text.ToString ();
416 public override string ReadToEnd()
418 if (base_stream == null)
419 throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
421 StringBuilder text = new StringBuilder ();
423 int size = decoded_buffer.Length;
424 char [] buffer = new char [size];
427 while ((len = Read (buffer, 0, size)) != 0)
428 text.Append (buffer, 0, len);
430 return text.ToString ();