StreamWriter.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. //
  2. // System.IO.StreamWriter.cs
  3. //
  4. // Authors:
  5. // Dietmar Maurer ([email protected])
  6. // Paolo Molaro ([email protected])
  7. //
  8. // (C) Ximian, Inc. http://www.ximian.com
  9. //
  10. using System.Text;
  11. using System;
  12. namespace System.IO {
  13. [Serializable]
  14. public class StreamWriter : TextWriter {
  15. private Encoding internalEncoding;
  16. private Stream internalStream;
  17. private bool closed = false;
  18. private bool iflush;
  19. private const int DefaultBufferSize = 1024;
  20. private const int DefaultFileBufferSize = 4096;
  21. private const int MinimumBufferSize = 256;
  22. private byte[] byte_buf;
  23. private int byte_pos;
  24. private char[] decode_buf;
  25. private int decode_pos;
  26. private bool DisposedAlready = false;
  27. private bool preamble_done = false;
  28. public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8Unmarked, 0);
  29. public StreamWriter (Stream stream)
  30. : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}
  31. public StreamWriter (Stream stream, Encoding encoding)
  32. : this (stream, encoding, DefaultBufferSize) {}
  33. internal void Initialize(Encoding encoding, int bufferSize) {
  34. internalEncoding = encoding;
  35. decode_pos = byte_pos = 0;
  36. int BufferSize = Math.Max(bufferSize, MinimumBufferSize);
  37. decode_buf = new char [BufferSize];
  38. byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];
  39. }
  40. //[MonoTODO("Nothing is done with bufferSize")]
  41. public StreamWriter (Stream stream, Encoding encoding, int bufferSize) {
  42. if (null == stream)
  43. throw new ArgumentNullException("stream");
  44. if (null == encoding)
  45. throw new ArgumentNullException("encoding");
  46. if (bufferSize < 0)
  47. throw new ArgumentOutOfRangeException("bufferSize");
  48. if (!stream.CanWrite)
  49. throw new ArgumentException("Can not write to stream", "stream");
  50. internalStream = stream;
  51. Initialize(encoding, bufferSize);
  52. }
  53. public StreamWriter (string path)
  54. : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}
  55. public StreamWriter (string path, bool append)
  56. : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}
  57. public StreamWriter (string path, bool append, Encoding encoding)
  58. : this (path, append, encoding, DefaultFileBufferSize) {}
  59. public StreamWriter (string path, bool append, Encoding encoding, int bufferSize) {
  60. if (null == path)
  61. throw new ArgumentNullException("path");
  62. if (String.Empty == path)
  63. throw new ArgumentException("path cannot be empty string");
  64. if (path.IndexOfAny (Path.InvalidPathChars) != -1)
  65. throw new ArgumentException("path contains invalid characters");
  66. if (null == encoding)
  67. throw new ArgumentNullException("encoding");
  68. if (bufferSize < 0)
  69. throw new ArgumentOutOfRangeException("bufferSize");
  70. string DirName = Path.GetDirectoryName(path);
  71. if (DirName != String.Empty && !Directory.Exists(DirName))
  72. throw new DirectoryNotFoundException();
  73. FileMode mode;
  74. if (append)
  75. mode = FileMode.Append;
  76. else
  77. mode = FileMode.Create;
  78. internalStream = new FileStream (path, mode, FileAccess.Write);
  79. if (append)
  80. internalStream.Position = internalStream.Length;
  81. else
  82. internalStream.SetLength (0);
  83. Initialize(encoding, bufferSize);
  84. }
  85. public virtual bool AutoFlush {
  86. get {
  87. return iflush;
  88. }
  89. set {
  90. iflush = value;
  91. }
  92. }
  93. public virtual Stream BaseStream {
  94. get {
  95. return internalStream;
  96. }
  97. }
  98. public override Encoding Encoding {
  99. get {
  100. return internalEncoding;
  101. }
  102. }
  103. protected override void Dispose (bool disposing) {
  104. if (!DisposedAlready && disposing && internalStream != null) {
  105. Flush();
  106. DisposedAlready = true;
  107. internalStream.Close ();
  108. }
  109. internalStream = null;
  110. byte_buf = null;
  111. internalEncoding = null;
  112. decode_buf = null;
  113. }
  114. public override void Flush () {
  115. if (DisposedAlready)
  116. throw new ObjectDisposedException("StreamWriter");
  117. Decode ();
  118. if (byte_pos > 0) {
  119. FlushBytes ();
  120. internalStream.Flush ();
  121. }
  122. }
  123. // how the speedup works:
  124. // the Write () methods simply copy the characters in a buffer of chars (decode_buf)
  125. // Decode () is called when the buffer is full or we need to flash.
  126. // Decode () will use the encoding to get the bytes and but them inside
  127. // byte_buf. From byte_buf the data is finally outputted to the stream.
  128. void FlushBytes () {
  129. // write the encoding preamble only at the start of the stream
  130. if (!preamble_done && byte_pos > 0) {
  131. byte[] preamble = internalEncoding.GetPreamble ();
  132. if (preamble.Length > 0)
  133. internalStream.Write (preamble, 0, preamble.Length);
  134. preamble_done = true;
  135. }
  136. internalStream.Write (byte_buf, 0, byte_pos);
  137. byte_pos = 0;
  138. }
  139. void Decode () {
  140. if (byte_pos > 0)
  141. FlushBytes ();
  142. if (decode_pos > 0) {
  143. int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
  144. byte_pos += len;
  145. decode_pos = 0;
  146. }
  147. }
  148. public override void Write (char[] buffer, int index, int count) {
  149. if (DisposedAlready)
  150. throw new ObjectDisposedException("StreamWriter");
  151. if (buffer == null)
  152. throw new ArgumentNullException ("buffer");
  153. if (index < 0 || index > buffer.Length)
  154. throw new ArgumentOutOfRangeException ("index");
  155. if (count < 0 || (index + count) > buffer.Length)
  156. throw new ArgumentOutOfRangeException ("count");
  157. LowLevelWrite (buffer, index, count);
  158. if (iflush)
  159. Flush();
  160. }
  161. void LowLevelWrite (char[] buffer, int index, int count) {
  162. while (count > 0) {
  163. int todo = decode_buf.Length - decode_pos;
  164. if (todo == 0) {
  165. Decode ();
  166. todo = decode_buf.Length;
  167. }
  168. if (todo > count)
  169. todo = count;
  170. Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
  171. count -= todo;
  172. index += todo;
  173. decode_pos += todo;
  174. }
  175. }
  176. public override void Write (char value)
  177. {
  178. // the size of decode_buf is always > 0 and
  179. // we check for overflow right away
  180. if (decode_pos >= decode_buf.Length)
  181. Decode ();
  182. decode_buf [decode_pos++] = value;
  183. if (iflush)
  184. Flush ();
  185. }
  186. public override void Write (char [] value)
  187. {
  188. LowLevelWrite (value, 0, value.Length);
  189. if (iflush)
  190. Flush ();
  191. }
  192. public override void Write (string value) {
  193. if (DisposedAlready)
  194. throw new ObjectDisposedException("StreamWriter");
  195. if (value != null)
  196. LowLevelWrite (value.ToCharArray (), 0, value.Length);
  197. if (iflush)
  198. Flush ();
  199. }
  200. public override void WriteLine (string value) {
  201. if (DisposedAlready)
  202. throw new ObjectDisposedException("StreamWriter");
  203. if (value != null)
  204. LowLevelWrite (value.ToCharArray (), 0, value.Length);
  205. string nl = NewLine;
  206. LowLevelWrite (nl.ToCharArray (), 0, nl.Length);
  207. if (iflush)
  208. Flush ();
  209. }
  210. public override void Close()
  211. {
  212. Dispose (true);
  213. }
  214. ~StreamWriter() {
  215. Dispose(false);
  216. }
  217. }
  218. }