2 // System.IO.StreamWriter.cs
\r
5 // Dietmar Maurer (dietmar@ximian.com)
\r
6 // Paolo Molaro (lupus@ximian.com)
\r
7 // Marek Safar (marek.safar@gmail.com)
\r
9 // (C) Ximian, Inc. http://www.ximian.com
\r
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
\r
11 // Copyright 2011 Xamarin Inc.
\r
13 // Permission is hereby granted, free of charge, to any person obtaining
\r
14 // a copy of this software and associated documentation files (the
\r
15 // "Software"), to deal in the Software without restriction, including
\r
16 // without limitation the rights to use, copy, modify, merge, publish,
\r
17 // distribute, sublicense, and/or sell copies of the Software, and to
\r
18 // permit persons to whom the Software is furnished to do so, subject to
\r
19 // the following conditions:
\r
21 // The above copyright notice and this permission notice shall be
\r
22 // included in all copies or substantial portions of the Software.
\r
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
\r
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
\r
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
\r
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
\r
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
\r
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
\r
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\r
34 using System.Runtime.InteropServices;
\r
36 using System.Threading.Tasks;
39 namespace System.IO {
\r
43 public class StreamWriter : TextWriter {
\r
45 private Encoding internalEncoding;
\r
47 private Stream internalStream;
\r
49 private const int DefaultBufferSize = 1024;
\r
50 private const int DefaultFileBufferSize = 4096;
\r
51 private const int MinimumBufferSize = 256;
\r
53 private byte[] byte_buf;
\r
54 private char[] decode_buf;
\r
55 private int byte_pos;
\r
56 private int decode_pos;
\r
58 private bool iflush;
\r
59 private bool DisposedAlready;
\r
60 private bool preamble_done;
\r
63 readonly bool leave_open;
\r
67 public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8Unmarked, 1);
\r
69 public StreamWriter (Stream stream)
\r
70 : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}
\r
72 public StreamWriter (Stream stream, Encoding encoding)
\r
73 : this (stream, encoding, DefaultBufferSize) {}
\r
75 internal void Initialize(Encoding encoding, int bufferSize) {
\r
76 internalEncoding = encoding;
\r
77 decode_pos = byte_pos = 0;
\r
78 int BufferSize = Math.Max(bufferSize, MinimumBufferSize);
\r
79 decode_buf = new char [BufferSize];
\r
80 byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];
\r
82 // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513
\r
83 if (internalStream.CanSeek && internalStream.Position > 0)
\r
84 preamble_done = true;
\r
88 public StreamWriter (Stream stream, Encoding encoding, int bufferSize)
\r
89 : this (stream, encoding, bufferSize, false)
\r
93 public StreamWriter (Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
\r
95 const bool leave_open = false;
\r
97 public StreamWriter (Stream stream, Encoding encoding, int bufferSize)
\r
100 if (null == stream)
\r
101 throw new ArgumentNullException("stream");
\r
102 if (null == encoding)
\r
103 throw new ArgumentNullException("encoding");
\r
104 if (bufferSize <= 0)
\r
105 throw new ArgumentOutOfRangeException("bufferSize");
\r
106 if (!stream.CanWrite)
\r
107 throw new ArgumentException ("Can not write to stream");
\r
110 leave_open = leaveOpen;
\r
112 internalStream = stream;
\r
114 Initialize(encoding, bufferSize);
\r
117 public StreamWriter (string path)
\r
118 : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}
\r
120 public StreamWriter (string path, bool append)
\r
121 : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}
\r
123 public StreamWriter (string path, bool append, Encoding encoding)
\r
124 : this (path, append, encoding, DefaultFileBufferSize) {}
\r
126 public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)
\r
128 if (null == encoding)
\r
129 throw new ArgumentNullException("encoding");
\r
130 if (bufferSize <= 0)
\r
131 throw new ArgumentOutOfRangeException("bufferSize");
\r
136 mode = FileMode.Append;
\r
138 mode = FileMode.Create;
\r
140 internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);
\r
143 internalStream.Position = internalStream.Length;
\r
145 internalStream.SetLength (0);
\r
147 Initialize(encoding, bufferSize);
\r
150 public virtual bool AutoFlush {
\r
161 public virtual Stream BaseStream {
\r
163 return internalStream;
\r
167 public override Encoding Encoding {
\r
169 return internalEncoding;
\r
173 protected override void Dispose (bool disposing)
\r
175 Exception exc = null;
\r
176 if (!DisposedAlready && disposing && internalStream != null && !leave_open) {
\r
179 } catch (Exception e) {
\r
182 DisposedAlready = true;
\r
184 internalStream.Close ();
\r
185 } catch (Exception e) {
\r
191 internalStream = null;
\r
193 internalEncoding = null;
\r
199 public override void Flush ()
\r
204 if (byte_pos > 0) {
\r
206 internalStream.Flush ();
\r
210 // how the speedup works:
\r
211 // the Write () methods simply copy the characters in a buffer of chars (decode_buf)
\r
212 // Decode () is called when the buffer is full or we need to flash.
\r
213 // Decode () will use the encoding to get the bytes and but them inside
\r
214 // byte_buf. From byte_buf the data is finally outputted to the stream.
\r
215 void FlushBytes ()
\r
217 // write the encoding preamble only at the start of the stream
\r
218 if (!preamble_done && byte_pos > 0) {
\r
219 byte[] preamble = internalEncoding.GetPreamble ();
\r
220 if (preamble.Length > 0)
\r
221 internalStream.Write (preamble, 0, preamble.Length);
\r
222 preamble_done = true;
\r
224 internalStream.Write (byte_buf, 0, byte_pos);
\r
232 if (decode_pos > 0) {
\r
233 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
\r
239 public override void Write (char[] buffer, int index, int count)
\r
241 if (buffer == null)
\r
242 throw new ArgumentNullException ("buffer");
\r
244 throw new ArgumentOutOfRangeException ("index", "< 0");
\r
246 throw new ArgumentOutOfRangeException ("count", "< 0");
\r
247 // re-ordered to avoid possible integer overflow
\r
248 if (index > buffer.Length - count)
\r
249 throw new ArgumentException ("index + count > buffer.Length");
\r
253 LowLevelWrite (buffer, index, count);
\r
258 void LowLevelWrite (char[] buffer, int index, int count)
\r
260 while (count > 0) {
\r
261 int todo = decode_buf.Length - decode_pos;
\r
264 todo = decode_buf.Length;
\r
268 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
\r
271 decode_pos += todo;
\r
275 void LowLevelWrite (string s)
\r
277 int count = s.Length;
\r
279 while (count > 0) {
\r
280 int todo = decode_buf.Length - decode_pos;
\r
283 todo = decode_buf.Length;
\r
288 for (int i = 0; i < todo; i ++)
\r
289 decode_buf [i + decode_pos] = s [i + index];
\r
293 decode_pos += todo;
\r
297 public override void Write (char value)
\r
301 // the size of decode_buf is always > 0 and
\r
302 // we check for overflow right away
\r
303 if (decode_pos >= decode_buf.Length)
\r
305 decode_buf [decode_pos++] = value;
\r
310 public override void Write (char[] buffer)
\r
314 if (buffer != null)
\r
315 LowLevelWrite (buffer, 0, buffer.Length);
\r
320 public override void Write (string value)
\r
325 LowLevelWrite (value);
\r
331 public override void Close()
\r
343 if (DisposedAlready)
\r
344 throw new ObjectDisposedException ("StreamWriter");
\r
347 if (async_task != null && async_task.IsCompleted)
\r
348 throw new InvalidOperationException ();
\r
353 public override Task FlushAsync ()
\r
356 return async_task = base.FlushAsync ();
\r
359 public override Task WriteAsync (char value)
\r
362 return async_task = base.WriteAsync (value);
\r
365 public override Task WriteAsync (char[] buffer, int index, int count)
\r
368 return async_task = base.WriteAsync (buffer, index, count);
\r
371 public override Task WriteAsync (string value)
\r
374 return async_task = base.WriteAsync (value);
\r
377 public override Task WriteLineAsync ()
\r
380 return async_task = base.WriteLineAsync ();
\r
383 public override Task WriteLineAsync (char value)
\r
386 return async_task = base.WriteLineAsync (value);
\r
389 public override Task WriteLineAsync (char[] buffer, int index, int count)
\r
392 return async_task = base.WriteLineAsync (buffer, index, count);
\r
395 public override Task WriteLineAsync (string value)
\r
398 return async_task = base.WriteLineAsync (value);
\r