mscorlib(4.0.0.0) API with additions
StreamWriter.cs
3 using System.Security;
5 using System.Text;
6 using System.Threading;
8 
9 namespace System.IO
10 {
12  [Serializable]
13  [ComVisible(true)]
14  [__DynamicallyInvokable]
15  public class StreamWriter : TextWriter
16  {
17  private sealed class MdaHelper
18  {
19  private StreamWriter streamWriter;
20 
21  private string allocatedCallstack;
22 
23  internal MdaHelper(StreamWriter sw, string cs)
24  {
25  streamWriter = sw;
26  allocatedCallstack = cs;
27  }
28 
29  ~MdaHelper()
30  {
31  if (streamWriter.charPos != 0 && (streamWriter.stream != null && streamWriter.stream != Stream.Null))
32  {
33  string text = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>";
34  string resourceString = allocatedCallstack;
35  if (resourceString == null)
36  {
37  resourceString = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled");
38  }
39  string resourceString2 = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, text, resourceString);
40  Mda.StreamWriterBufferedDataLost.ReportError(resourceString2);
41  }
42  }
43  }
44 
45  internal const int DefaultBufferSize = 1024;
46 
47  private const int DefaultFileStreamBufferSize = 4096;
48 
49  private const int MinBufferSize = 128;
50 
51  private const int DontCopyOnWriteLineThreshold = 512;
52 
54  [__DynamicallyInvokable]
55  public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), 128, leaveOpen: true);
56 
57  private Stream stream;
58 
59  private Encoding encoding;
60 
61  private Encoder encoder;
62 
63  private byte[] byteBuffer;
64 
65  private char[] charBuffer;
66 
67  private int charPos;
68 
69  private int charLen;
70 
71  private bool autoFlush;
72 
73  private bool haveWrittenPreamble;
74 
75  private bool closable;
76 
77  [NonSerialized]
78  private MdaHelper mdaHelper;
79 
80  [NonSerialized]
81  private volatile Task _asyncWriteTask;
82 
83  private static volatile Encoding _UTF8NoBOM;
84 
85  internal static Encoding UTF8NoBOM
86  {
87  [FriendAccessAllowed]
88  get
89  {
90  if (_UTF8NoBOM == null)
91  {
92  UTF8Encoding uTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
94  _UTF8NoBOM = uTF8NoBOM;
95  }
96  return _UTF8NoBOM;
97  }
98  }
99 
103  [__DynamicallyInvokable]
104  public virtual bool AutoFlush
105  {
106  [__DynamicallyInvokable]
107  get
108  {
109  return autoFlush;
110  }
111  [__DynamicallyInvokable]
112  set
113  {
114  CheckAsyncTaskInProgress();
115  autoFlush = value;
116  if (value)
117  {
118  Flush(flushStream: true, flushEncoder: false);
119  }
120  }
121  }
122 
125  [__DynamicallyInvokable]
126  public virtual Stream BaseStream
127  {
128  [__DynamicallyInvokable]
129  get
130  {
131  return stream;
132  }
133  }
134 
135  internal bool LeaveOpen => !closable;
136 
137  internal bool HaveWrittenPreamble
138  {
139  set
140  {
141  haveWrittenPreamble = value;
142  }
143  }
144 
147  [__DynamicallyInvokable]
148  public override Encoding Encoding
149  {
150  [__DynamicallyInvokable]
151  get
152  {
153  return encoding;
154  }
155  }
156 
157  private int CharPos_Prop
158  {
159  set
160  {
161  charPos = value;
162  }
163  }
164 
165  private bool HaveWrittenPreamble_Prop
166  {
167  set
168  {
169  haveWrittenPreamble = value;
170  }
171  }
172 
173  private void CheckAsyncTaskInProgress()
174  {
175  Task asyncWriteTask = _asyncWriteTask;
176  if (asyncWriteTask != null && !asyncWriteTask.IsCompleted)
177  {
178  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress"));
179  }
180  }
181 
182  internal StreamWriter()
183  : base(null)
184  {
185  }
186 
193  [__DynamicallyInvokable]
194  public StreamWriter(Stream stream)
195  : this(stream, UTF8NoBOM, 1024, leaveOpen: false)
196  {
197  }
198 
206  [__DynamicallyInvokable]
207  public StreamWriter(Stream stream, Encoding encoding)
208  : this(stream, encoding, 1024, leaveOpen: false)
209  {
210  }
211 
222  [__DynamicallyInvokable]
223  public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
224  : this(stream, encoding, bufferSize, leaveOpen: false)
225  {
226  }
227 
240  [__DynamicallyInvokable]
241  public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
242  : base(null)
243  {
244  if (stream == null || encoding == null)
245  {
246  throw new ArgumentNullException((stream == null) ? "stream" : "encoding");
247  }
248  if (!stream.CanWrite)
249  {
250  throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
251  }
252  if (bufferSize <= 0)
253  {
254  throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
255  }
256  Init(stream, encoding, bufferSize, leaveOpen);
257  }
258 
272  public StreamWriter(string path)
273  : this(path, append: false, UTF8NoBOM, 1024)
274  {
275  }
276 
292  public StreamWriter(string path, bool append)
293  : this(path, append, UTF8NoBOM, 1024)
294  {
295  }
296 
313  public StreamWriter(string path, bool append, Encoding encoding)
314  : this(path, append, encoding, 1024)
315  {
316  }
317 
337  [SecuritySafeCritical]
338  public StreamWriter(string path, bool append, Encoding encoding, int bufferSize)
339  : this(path, append, encoding, bufferSize, checkHost: true)
340  {
341  }
342 
343  [SecurityCritical]
344  internal StreamWriter(string path, bool append, Encoding encoding, int bufferSize, bool checkHost)
345  : base(null)
346  {
347  if (path == null)
348  {
349  throw new ArgumentNullException("path");
350  }
351  if (encoding == null)
352  {
353  throw new ArgumentNullException("encoding");
354  }
355  if (path.Length == 0)
356  {
357  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
358  }
359  if (bufferSize <= 0)
360  {
361  throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
362  }
363  Stream streamArg = CreateFile(path, append, checkHost);
364  Init(streamArg, encoding, bufferSize, shouldLeaveOpen: false);
365  }
366 
367  [SecuritySafeCritical]
368  private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
369  {
370  stream = streamArg;
371  encoding = encodingArg;
372  encoder = encoding.GetEncoder();
373  if (bufferSize < 128)
374  {
375  bufferSize = 128;
376  }
377  charBuffer = new char[bufferSize];
378  byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)];
379  charLen = bufferSize;
380  if (stream.CanSeek && stream.Position > 0)
381  {
382  haveWrittenPreamble = true;
383  }
384  closable = !shouldLeaveOpen;
385  if (Mda.StreamWriterBufferedDataLost.Enabled)
386  {
387  string cs = null;
388  if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
389  {
390  cs = Environment.GetStackTrace(null, needFileInfo: false);
391  }
392  mdaHelper = new MdaHelper(this, cs);
393  }
394  }
395 
396  [SecurityCritical]
397  private static Stream CreateFile(string path, bool append, bool checkHost)
398  {
399  FileMode mode = append ? FileMode.Append : FileMode.Create;
400  return new FileStream(path, mode, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan, Path.GetFileName(path), bFromProxy: false, useLongPath: false, checkHost);
401  }
402 
405  public override void Close()
406  {
407  Dispose(disposing: true);
408  GC.SuppressFinalize(this);
409  }
410 
415  [__DynamicallyInvokable]
416  protected override void Dispose(bool disposing)
417  {
418  try
419  {
420  if (stream != null && (disposing || (LeaveOpen && stream is __ConsoleStream)))
421  {
422  CheckAsyncTaskInProgress();
423  Flush(flushStream: true, flushEncoder: true);
424  if (mdaHelper != null)
425  {
426  GC.SuppressFinalize(mdaHelper);
427  }
428  }
429  }
430  finally
431  {
432  if (!LeaveOpen && stream != null)
433  {
434  try
435  {
436  if (disposing)
437  {
438  stream.Close();
439  }
440  }
441  finally
442  {
443  stream = null;
444  byteBuffer = null;
445  charBuffer = null;
446  encoding = null;
447  encoder = null;
448  charLen = 0;
449  base.Dispose(disposing);
450  }
451  }
452  }
453  }
454 
459  [__DynamicallyInvokable]
460  public override void Flush()
461  {
462  CheckAsyncTaskInProgress();
463  Flush(flushStream: true, flushEncoder: true);
464  }
465 
466  private void Flush(bool flushStream, bool flushEncoder)
467  {
468  if (stream == null)
469  {
470  __Error.WriterClosed();
471  }
472  if (charPos == 0 && ((!flushStream && !flushEncoder) || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8))
473  {
474  return;
475  }
476  if (!haveWrittenPreamble)
477  {
478  haveWrittenPreamble = true;
479  byte[] preamble = encoding.GetPreamble();
480  if (preamble.Length != 0)
481  {
482  stream.Write(preamble, 0, preamble.Length);
483  }
484  }
485  int bytes = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
486  charPos = 0;
487  if (bytes > 0)
488  {
489  stream.Write(byteBuffer, 0, bytes);
490  }
491  if (flushStream)
492  {
493  stream.Flush();
494  }
495  }
496 
504  [__DynamicallyInvokable]
505  public override void Write(char value)
506  {
507  CheckAsyncTaskInProgress();
508  if (charPos == charLen)
509  {
510  Flush(flushStream: false, flushEncoder: false);
511  }
512  charBuffer[charPos] = value;
513  charPos++;
514  if (autoFlush)
515  {
516  Flush(flushStream: true, flushEncoder: false);
517  }
518  }
519 
527  [__DynamicallyInvokable]
528  public override void Write(char[] buffer)
529  {
530  if (buffer == null)
531  {
532  return;
533  }
534  CheckAsyncTaskInProgress();
535  int num = 0;
536  int num3;
537  for (int num2 = buffer.Length; num2 > 0; num2 -= num3)
538  {
539  if (charPos == charLen)
540  {
541  Flush(flushStream: false, flushEncoder: false);
542  }
543  num3 = charLen - charPos;
544  if (num3 > num2)
545  {
546  num3 = num2;
547  }
548  Buffer.InternalBlockCopy(buffer, num * 2, charBuffer, charPos * 2, num3 * 2);
549  charPos += num3;
550  num += num3;
551  }
552  if (autoFlush)
553  {
554  Flush(flushStream: true, flushEncoder: false);
555  }
556  }
557 
572  [__DynamicallyInvokable]
573  public override void Write(char[] buffer, int index, int count)
574  {
575  if (buffer == null)
576  {
577  throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
578  }
579  if (index < 0)
580  {
581  throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
582  }
583  if (count < 0)
584  {
585  throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
586  }
587  if (buffer.Length - index < count)
588  {
589  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
590  }
591  CheckAsyncTaskInProgress();
592  while (count > 0)
593  {
594  if (charPos == charLen)
595  {
596  Flush(flushStream: false, flushEncoder: false);
597  }
598  int num = charLen - charPos;
599  if (num > count)
600  {
601  num = count;
602  }
603  Buffer.InternalBlockCopy(buffer, index * 2, charBuffer, charPos * 2, num * 2);
604  charPos += num;
605  index += num;
606  count -= num;
607  }
608  if (autoFlush)
609  {
610  Flush(flushStream: true, flushEncoder: false);
611  }
612  }
613 
621  [__DynamicallyInvokable]
622  public override void Write(string value)
623  {
624  if (value == null)
625  {
626  return;
627  }
628  CheckAsyncTaskInProgress();
629  int num = value.Length;
630  int num2 = 0;
631  while (num > 0)
632  {
633  if (charPos == charLen)
634  {
635  Flush(flushStream: false, flushEncoder: false);
636  }
637  int num3 = charLen - charPos;
638  if (num3 > num)
639  {
640  num3 = num;
641  }
642  value.CopyTo(num2, charBuffer, charPos, num3);
643  charPos += num3;
644  num2 += num3;
645  num -= num3;
646  }
647  if (autoFlush)
648  {
649  Flush(flushStream: true, flushEncoder: false);
650  }
651  }
652 
658  [ComVisible(false)]
659  [__DynamicallyInvokable]
660  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
661  public override Task WriteAsync(char value)
662  {
663  if (GetType() != typeof(StreamWriter))
664  {
665  return base.WriteAsync(value);
666  }
667  if (stream == null)
668  {
669  __Error.WriterClosed();
670  }
671  CheckAsyncTaskInProgress();
672  return _asyncWriteTask = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
673  }
674 
675  private static async Task WriteAsyncInternal(StreamWriter _this, char value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine)
676  {
677  if (charPos == charLen)
678  {
679  await _this.FlushAsyncInternal(flushStream: false, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
680  charPos = 0;
681  }
682  charBuffer[charPos] = value;
683  charPos++;
684  if (appendNewLine)
685  {
686  for (int i = 0; i < coreNewLine.Length; i++)
687  {
688  if (charPos == charLen)
689  {
690  await _this.FlushAsyncInternal(flushStream: false, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
691  charPos = 0;
692  }
693  charBuffer[charPos] = coreNewLine[i];
694  charPos++;
695  }
696  }
697  if (autoFlush)
698  {
699  await _this.FlushAsyncInternal(flushStream: true, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
700  charPos = 0;
701  }
702  _this.CharPos_Prop = charPos;
703  }
704 
710  [ComVisible(false)]
711  [__DynamicallyInvokable]
712  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
713  public override Task WriteAsync(string value)
714  {
715  if (GetType() != typeof(StreamWriter))
716  {
717  return base.WriteAsync(value);
718  }
719  if (value != null)
720  {
721  if (stream == null)
722  {
723  __Error.WriterClosed();
724  }
725  CheckAsyncTaskInProgress();
726  return _asyncWriteTask = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
727  }
728  return Task.CompletedTask;
729  }
730 
731  private static async Task WriteAsyncInternal(StreamWriter _this, string value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine)
732  {
733  int count = value.Length;
734  int index = 0;
735  while (count > 0)
736  {
737  if (charPos == charLen)
738  {
739  await _this.FlushAsyncInternal(flushStream: false, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
740  charPos = 0;
741  }
742  int num = charLen - charPos;
743  if (num > count)
744  {
745  num = count;
746  }
747  value.CopyTo(index, charBuffer, charPos, num);
748  charPos += num;
749  index += num;
750  count -= num;
751  }
752  if (appendNewLine)
753  {
754  for (int i = 0; i < coreNewLine.Length; i++)
755  {
756  if (charPos == charLen)
757  {
758  await _this.FlushAsyncInternal(flushStream: false, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
759  charPos = 0;
760  }
761  charBuffer[charPos] = coreNewLine[i];
762  charPos++;
763  }
764  }
765  if (autoFlush)
766  {
767  await _this.FlushAsyncInternal(flushStream: true, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
768  charPos = 0;
769  }
770  _this.CharPos_Prop = charPos;
771  }
772 
785  [ComVisible(false)]
786  [__DynamicallyInvokable]
787  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
788  public override Task WriteAsync(char[] buffer, int index, int count)
789  {
790  if (buffer == null)
791  {
792  throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
793  }
794  if (index < 0)
795  {
796  throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
797  }
798  if (count < 0)
799  {
800  throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
801  }
802  if (buffer.Length - index < count)
803  {
804  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
805  }
806  if (GetType() != typeof(StreamWriter))
807  {
808  return base.WriteAsync(buffer, index, count);
809  }
810  if (stream == null)
811  {
812  __Error.WriterClosed();
813  }
814  CheckAsyncTaskInProgress();
815  return _asyncWriteTask = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
816  }
817 
818  private static async Task WriteAsyncInternal(StreamWriter _this, char[] buffer, int index, int count, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine)
819  {
820  while (count > 0)
821  {
822  if (charPos == charLen)
823  {
824  await _this.FlushAsyncInternal(flushStream: false, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
825  charPos = 0;
826  }
827  int num = charLen - charPos;
828  if (num > count)
829  {
830  num = count;
831  }
832  Buffer.InternalBlockCopy(buffer, index * 2, charBuffer, charPos * 2, num * 2);
833  charPos += num;
834  index += num;
835  count -= num;
836  }
837  if (appendNewLine)
838  {
839  for (int i = 0; i < coreNewLine.Length; i++)
840  {
841  if (charPos == charLen)
842  {
843  await _this.FlushAsyncInternal(flushStream: false, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
844  charPos = 0;
845  }
846  charBuffer[charPos] = coreNewLine[i];
847  charPos++;
848  }
849  }
850  if (autoFlush)
851  {
852  await _this.FlushAsyncInternal(flushStream: true, flushEncoder: false, charBuffer, charPos).ConfigureAwait(continueOnCapturedContext: false);
853  charPos = 0;
854  }
855  _this.CharPos_Prop = charPos;
856  }
857 
862  [ComVisible(false)]
863  [__DynamicallyInvokable]
864  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
865  public override Task WriteLineAsync()
866  {
867  if (GetType() != typeof(StreamWriter))
868  {
869  return base.WriteLineAsync();
870  }
871  if (stream == null)
872  {
873  __Error.WriterClosed();
874  }
875  CheckAsyncTaskInProgress();
876  return _asyncWriteTask = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
877  }
878 
884  [ComVisible(false)]
885  [__DynamicallyInvokable]
886  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
887  public override Task WriteLineAsync(char value)
888  {
889  if (GetType() != typeof(StreamWriter))
890  {
891  return base.WriteLineAsync(value);
892  }
893  if (stream == null)
894  {
895  __Error.WriterClosed();
896  }
897  CheckAsyncTaskInProgress();
898  return _asyncWriteTask = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
899  }
900 
906  [ComVisible(false)]
907  [__DynamicallyInvokable]
908  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
909  public override Task WriteLineAsync(string value)
910  {
911  if (GetType() != typeof(StreamWriter))
912  {
913  return base.WriteLineAsync(value);
914  }
915  if (stream == null)
916  {
917  __Error.WriterClosed();
918  }
919  CheckAsyncTaskInProgress();
920  return _asyncWriteTask = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
921  }
922 
935  [ComVisible(false)]
936  [__DynamicallyInvokable]
937  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
938  public override Task WriteLineAsync(char[] buffer, int index, int count)
939  {
940  if (buffer == null)
941  {
942  throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
943  }
944  if (index < 0)
945  {
946  throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
947  }
948  if (count < 0)
949  {
950  throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
951  }
952  if (buffer.Length - index < count)
953  {
954  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
955  }
956  if (GetType() != typeof(StreamWriter))
957  {
958  return base.WriteLineAsync(buffer, index, count);
959  }
960  if (stream == null)
961  {
962  __Error.WriterClosed();
963  }
964  CheckAsyncTaskInProgress();
965  return _asyncWriteTask = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
966  }
967 
971  [ComVisible(false)]
972  [__DynamicallyInvokable]
973  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
974  public override Task FlushAsync()
975  {
976  if (GetType() != typeof(StreamWriter))
977  {
978  return base.FlushAsync();
979  }
980  if (stream == null)
981  {
982  __Error.WriterClosed();
983  }
984  CheckAsyncTaskInProgress();
985  return _asyncWriteTask = FlushAsyncInternal(flushStream: true, flushEncoder: true, charBuffer, charPos);
986  }
987 
988  private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, char[] sCharBuffer, int sCharPos)
989  {
990  if (sCharPos == 0 && !flushStream && !flushEncoder)
991  {
992  return Task.CompletedTask;
993  }
994  Task result = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, haveWrittenPreamble, encoding, encoder, byteBuffer, stream);
995  charPos = 0;
996  return result;
997  }
998 
999  private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, char[] charBuffer, int charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, byte[] byteBuffer, Stream stream)
1000  {
1001  if (!haveWrittenPreamble)
1002  {
1003  _this.HaveWrittenPreamble_Prop = true;
1004  byte[] preamble = encoding.GetPreamble();
1005  if (preamble.Length != 0)
1006  {
1007  await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(continueOnCapturedContext: false);
1008  }
1009  }
1010  int bytes = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
1011  if (bytes > 0)
1012  {
1013  await stream.WriteAsync(byteBuffer, 0, bytes).ConfigureAwait(continueOnCapturedContext: false);
1014  }
1015  if (flushStream)
1016  {
1017  await stream.FlushAsync().ConfigureAwait(continueOnCapturedContext: false);
1018  }
1019  }
1020  }
1021 }
Represents a character encoding.To browse the .NET Framework source code for this type,...
Definition: Encoding.cs:15
override void Dispose(bool disposing)
Releases the unmanaged resources used by the T:System.IO.StreamWriter and optionally releases the man...
StreamWriter(string path, bool append, Encoding encoding, int bufferSize)
Initializes a new instance of the T:System.IO.StreamWriter class for the specified file on the specif...
abstract void Write(byte[] buffer, int offset, int count)
When overridden in a derived class, writes a sequence of bytes to the current stream and advances the...
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
new ConfiguredTaskAwaitable< TResult > ConfigureAwait(bool continueOnCapturedContext)
Configures an awaiter used to await this T:System.Threading.Tasks.Task`1.
Definition: Task.cs:393
Converts a set of characters into a sequence of bytes.
Definition: Encoder.cs:11
FileOptions
Represents advanced options for creating a T:System.IO.FileStream object.
Definition: FileOptions.cs:9
static void MemoryBarrier()
Synchronizes memory access as follows: The processor executing the current thread cannot reorder inst...
virtual Encoder GetEncoder()
When overridden in a derived class, obtains an encoder that converts a sequence of Unicode characters...
Definition: Encoding.cs:1972
abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush)
When overridden in a derived class, encodes a set of characters from the specified character array an...
StreamWriter(Stream stream, Encoding encoding, int bufferSize)
Initializes a new instance of the T:System.IO.StreamWriter class for the specified stream by using th...
static new readonly StreamWriter Null
Provides a StreamWriter with no backing store that can be written to, but not read from.
Definition: StreamWriter.cs:55
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
Definition: GC.cs:308
abstract bool CanSeek
When overridden in a derived class, gets a value indicating whether the current stream supports seeki...
Definition: Stream.cs:587
FileMode
Specifies how the operating system should open a file.
Definition: FileMode.cs:8
Definition: __Canon.cs:3
The exception that is thrown when the value of an argument is outside the allowable range of values a...
abstract bool CanWrite
When overridden in a derived class, gets a value indicating whether the current stream supports writi...
Definition: Stream.cs:610
override Task WriteLineAsync(string value)
Writes a string followed by a line terminator asynchronously to the stream.
void Dispose()
Releases all resources used by the T:System.IO.TextWriter object.
Definition: TextWriter.cs:507
override void Write(char[] buffer)
Writes a character array to the stream.
SecurityAction
Specifies the security actions that can be performed using declarative security.
Implements a T:System.IO.TextWriter for writing characters to a stream in a particular encoding....
Definition: StreamWriter.cs:15
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
virtual void Close()
Closes the current stream and releases any resources (such as sockets and file handles) associated wi...
Definition: Stream.cs:855
override Task WriteLineAsync()
Writes a line terminator asynchronously to the stream.
StreamWriter(string path, bool append)
Initializes a new instance of the T:System.IO.StreamWriter class for the specified file by using the ...
static readonly Stream Null
A Stream with no backing store.
Definition: Stream.cs:562
override void Write(char[] buffer, int index, int count)
Writes a subarray of characters to the stream.
bool IsCompleted
Gets whether this T:System.Threading.Tasks.Task has completed.
Definition: Task.cs:1370
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
Definition: FileStream.cs:15
Represents a writer that can write a sequential series of characters. This class is abstract.
Definition: TextWriter.cs:15
abstract void Flush()
When overridden in a derived class, clears all buffers for this stream and causes any buffered data t...
Represents a UTF-8 encoding of Unicode characters.
Definition: UTF8Encoding.cs:11
StreamWriter(Stream stream, Encoding encoding)
Initializes a new instance of the T:System.IO.StreamWriter class for the specified stream by using th...
static Task CompletedTask
Gets a task that has already completed successfully.
Definition: Task.cs:1453
StreamWriter(Stream stream)
Initializes a new instance of the T:System.IO.StreamWriter class for the specified stream by using UT...
virtual bool AutoFlush
Gets or sets a value indicating whether the T:System.IO.StreamWriter will flush its buffer to the und...
char [] CoreNewLine
Stores the newline characters used for this TextWriter.
Definition: TextWriter.cs:421
Controls the system garbage collector, a service that automatically reclaims unused memory.
Definition: GC.cs:11
StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
Initializes a new instance of the T:System.IO.StreamWriter class for the specified stream by using th...
The exception that is thrown when one of the arguments provided to a method is not valid.
override void Write(char value)
Writes a character to the stream.
override Task WriteAsync(char value)
Writes a character to the stream asynchronously.
virtual byte [] GetPreamble()
When overridden in a derived class, returns a sequence of bytes that specifies the encoding used.
Definition: Encoding.cs:1453
FileAccess
Defines constants for read, write, or read/write access to a file.
Definition: FileAccess.cs:9
StreamWriter(string path, bool append, Encoding encoding)
Initializes a new instance of the T:System.IO.StreamWriter class for the specified file by using the ...
virtual Stream BaseStream
Gets the underlying stream that interfaces with a backing store.
Specifies that the class can be serialized.
abstract long Position
When overridden in a derived class, gets or sets the position within the current stream.
Definition: Stream.cs:633
override Task FlushAsync()
Clears all buffers for this stream asynchronously and causes any buffered data to be written to the u...
Manipulates arrays of primitive types.
Definition: Buffer.cs:11
override Task WriteLineAsync(char value)
Writes a character followed by a line terminator asynchronously to the stream.
override void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlyin...
abstract int GetMaxByteCount(int charCount)
When overridden in a derived class, calculates the maximum number of bytes produced by encoding the s...
override void Write(string value)
Writes a string to the stream.
The P:System.Uri.LocalPath data.
override void Close()
Closes the current StreamWriter object and the underlying stream.
StreamWriter(string path)
Initializes a new instance of the T:System.IO.StreamWriter class for the specified file by using the ...
override Task WriteLineAsync(char[] buffer, int index, int count)
Writes a subarray of characters followed by a line terminator asynchronously to the stream.
override Task WriteAsync(string value)
Writes a string to the stream asynchronously.
override Task WriteAsync(char[] buffer, int index, int count)
Writes a subarray of characters to the stream asynchronously.
FileShare
Contains constants for controlling the kind of access other T:System.IO.FileStream objects can have t...
Definition: FileShare.cs:9
Represents an asynchronous operation that can return a value.
Definition: Task.cs:18
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Definition: Stream.cs:16
Creates and controls a thread, sets its priority, and gets its status.
Definition: Thread.cs:18