14 [__DynamicallyInvokable]
17 private sealed
class MdaHelper
21 private string allocatedCallstack;
26 allocatedCallstack = cs;
31 if (streamWriter.charPos != 0 && (streamWriter.stream !=
null && streamWriter.stream !=
Stream.
Null))
33 string text = (streamWriter.stream is
FileStream) ? ((
FileStream)streamWriter.stream).NameInternal :
"<unknown>";
34 string resourceString = allocatedCallstack;
35 if (resourceString ==
null)
37 resourceString =
Environment.GetResourceString(
"IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled");
39 string resourceString2 =
Environment.GetResourceString(
"IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, text, resourceString);
40 Mda.StreamWriterBufferedDataLost.ReportError(resourceString2);
45 internal const int DefaultBufferSize = 1024;
47 private const int DefaultFileStreamBufferSize = 4096;
49 private const int MinBufferSize = 128;
51 private const int DontCopyOnWriteLineThreshold = 512;
54 [__DynamicallyInvokable]
63 private byte[] byteBuffer;
65 private char[] charBuffer;
71 private bool autoFlush;
73 private bool haveWrittenPreamble;
75 private bool closable;
78 private MdaHelper mdaHelper;
81 private volatile Task _asyncWriteTask;
83 private static volatile Encoding _UTF8NoBOM;
90 if (_UTF8NoBOM ==
null)
94 _UTF8NoBOM = uTF8NoBOM;
103 [__DynamicallyInvokable]
106 [__DynamicallyInvokable]
111 [__DynamicallyInvokable]
114 CheckAsyncTaskInProgress();
118 Flush(flushStream:
true, flushEncoder:
false);
125 [__DynamicallyInvokable]
128 [__DynamicallyInvokable]
135 internal bool LeaveOpen => !closable;
137 internal bool HaveWrittenPreamble
141 haveWrittenPreamble = value;
147 [__DynamicallyInvokable]
150 [__DynamicallyInvokable]
157 private int CharPos_Prop
165 private bool HaveWrittenPreamble_Prop
169 haveWrittenPreamble = value;
173 private void CheckAsyncTaskInProgress()
175 Task asyncWriteTask = _asyncWriteTask;
176 if (asyncWriteTask !=
null && !asyncWriteTask.
IsCompleted)
178 throw new InvalidOperationException(Environment.GetResourceString(
"InvalidOperation_AsyncIOInProgress"));
182 internal StreamWriter()
193 [__DynamicallyInvokable]
195 : this(stream, UTF8NoBOM, 1024, leaveOpen: false)
206 [__DynamicallyInvokable]
208 : this(stream, encoding, 1024, leaveOpen: false)
222 [__DynamicallyInvokable]
224 : this(stream, encoding, bufferSize, leaveOpen: false)
240 [__DynamicallyInvokable]
244 if (stream ==
null || encoding ==
null)
256 Init(stream, encoding, bufferSize, leaveOpen);
273 : this(path, append: false, UTF8NoBOM, 1024)
293 : this(path, append, UTF8NoBOM, 1024)
314 : this(path, append, encoding, 1024)
337 [SecuritySafeCritical]
339 : this(path, append, encoding, bufferSize, checkHost: true)
344 internal StreamWriter(
string path,
bool append,
Encoding encoding,
int bufferSize,
bool checkHost)
351 if (encoding ==
null)
355 if (path.Length == 0)
357 throw new ArgumentException(Environment.GetResourceString(
"Argument_EmptyPath"));
361 throw new ArgumentOutOfRangeException(
"bufferSize", Environment.GetResourceString(
"ArgumentOutOfRange_NeedPosNum"));
363 Stream streamArg = CreateFile(path, append, checkHost);
364 Init(streamArg, encoding, bufferSize, shouldLeaveOpen:
false);
367 [SecuritySafeCritical]
368 private void Init(Stream streamArg,
Encoding encodingArg,
int bufferSize,
bool shouldLeaveOpen)
371 encoding = encodingArg;
373 if (bufferSize < 128)
377 charBuffer =
new char[bufferSize];
379 charLen = bufferSize;
382 haveWrittenPreamble =
true;
384 closable = !shouldLeaveOpen;
385 if (Mda.StreamWriterBufferedDataLost.Enabled)
388 if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
390 cs = Environment.GetStackTrace(
null, needFileInfo:
false);
392 mdaHelper =
new MdaHelper(
this, cs);
397 private static Stream CreateFile(
string path,
bool append,
bool checkHost)
400 return new FileStream(path, mode,
FileAccess.Write,
FileShare.Read, 4096,
FileOptions.SequentialScan,
Path.GetFileName(path), bFromProxy:
false, useLongPath:
false, checkHost);
415 [__DynamicallyInvokable]
416 protected override void Dispose(
bool disposing)
420 if (stream !=
null && (disposing || (LeaveOpen && stream is __ConsoleStream)))
422 CheckAsyncTaskInProgress();
423 Flush(flushStream:
true, flushEncoder:
true);
424 if (mdaHelper !=
null)
432 if (!LeaveOpen && stream !=
null)
449 base.Dispose(disposing);
459 [__DynamicallyInvokable]
462 CheckAsyncTaskInProgress();
463 Flush(flushStream:
true, flushEncoder:
true);
466 private void Flush(
bool flushStream,
bool flushEncoder)
470 __Error.WriterClosed();
472 if (charPos == 0 && ((!flushStream && !flushEncoder) || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8))
476 if (!haveWrittenPreamble)
478 haveWrittenPreamble =
true;
480 if (preamble.Length != 0)
482 stream.
Write(preamble, 0, preamble.Length);
485 int bytes = encoder.
GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
489 stream.
Write(byteBuffer, 0, bytes);
504 [__DynamicallyInvokable]
505 public override void Write(
char value)
507 CheckAsyncTaskInProgress();
508 if (charPos == charLen)
510 Flush(flushStream:
false, flushEncoder:
false);
512 charBuffer[charPos] = value;
516 Flush(flushStream:
true, flushEncoder:
false);
527 [__DynamicallyInvokable]
528 public override void Write(
char[] buffer)
534 CheckAsyncTaskInProgress();
537 for (
int num2 = buffer.Length; num2 > 0; num2 -= num3)
539 if (charPos == charLen)
541 Flush(flushStream:
false, flushEncoder:
false);
543 num3 = charLen - charPos;
548 Buffer.InternalBlockCopy(buffer, num * 2, charBuffer, charPos * 2, num3 * 2);
554 Flush(flushStream:
true, flushEncoder:
false);
572 [__DynamicallyInvokable]
573 public override void Write(
char[] buffer,
int index,
int count)
587 if (buffer.Length - index < count)
591 CheckAsyncTaskInProgress();
594 if (charPos == charLen)
596 Flush(flushStream:
false, flushEncoder:
false);
598 int num = charLen - charPos;
603 Buffer.InternalBlockCopy(buffer, index * 2, charBuffer, charPos * 2, num * 2);
610 Flush(flushStream:
true, flushEncoder:
false);
621 [__DynamicallyInvokable]
622 public override void Write(
string value)
628 CheckAsyncTaskInProgress();
629 int num = value.Length;
633 if (charPos == charLen)
635 Flush(flushStream:
false, flushEncoder:
false);
637 int num3 = charLen - charPos;
642 value.CopyTo(num2, charBuffer, charPos, num3);
649 Flush(flushStream:
true, flushEncoder:
false);
659 [__DynamicallyInvokable]
660 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
665 return base.WriteAsync(value);
669 __Error.WriterClosed();
671 CheckAsyncTaskInProgress();
672 return _asyncWriteTask = WriteAsyncInternal(
this, value, charBuffer, charPos, charLen,
CoreNewLine, autoFlush, appendNewLine:
false);
675 private static async
Task WriteAsyncInternal(
StreamWriter _this,
char value,
char[] charBuffer,
int charPos,
int charLen,
char[] coreNewLine,
bool autoFlush,
bool appendNewLine)
677 if (charPos == charLen)
679 await _this.FlushAsyncInternal(flushStream:
false, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
682 charBuffer[charPos] = value;
686 for (
int i = 0; i < coreNewLine.Length; i++)
688 if (charPos == charLen)
690 await _this.FlushAsyncInternal(flushStream:
false, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
693 charBuffer[charPos] = coreNewLine[i];
699 await _this.FlushAsyncInternal(flushStream:
true, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
702 _this.CharPos_Prop = charPos;
711 [__DynamicallyInvokable]
712 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
717 return base.WriteAsync(value);
723 __Error.WriterClosed();
725 CheckAsyncTaskInProgress();
726 return _asyncWriteTask = WriteAsyncInternal(
this, value, charBuffer, charPos, charLen,
CoreNewLine, autoFlush, appendNewLine:
false);
731 private static async
Task WriteAsyncInternal(
StreamWriter _this,
string value,
char[] charBuffer,
int charPos,
int charLen,
char[] coreNewLine,
bool autoFlush,
bool appendNewLine)
733 int count = value.Length;
737 if (charPos == charLen)
739 await _this.FlushAsyncInternal(flushStream:
false, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
742 int num = charLen - charPos;
747 value.CopyTo(index, charBuffer, charPos, num);
754 for (
int i = 0; i < coreNewLine.Length; i++)
756 if (charPos == charLen)
758 await _this.FlushAsyncInternal(flushStream:
false, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
761 charBuffer[charPos] = coreNewLine[i];
767 await _this.FlushAsyncInternal(flushStream:
true, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
770 _this.CharPos_Prop = charPos;
786 [__DynamicallyInvokable]
787 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
802 if (buffer.Length - index < count)
808 return base.WriteAsync(buffer, index, count);
812 __Error.WriterClosed();
814 CheckAsyncTaskInProgress();
815 return _asyncWriteTask = WriteAsyncInternal(
this, buffer, index, count, charBuffer, charPos, charLen,
CoreNewLine, autoFlush, appendNewLine:
false);
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)
822 if (charPos == charLen)
824 await _this.FlushAsyncInternal(flushStream:
false, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
827 int num = charLen - charPos;
832 Buffer.InternalBlockCopy(buffer, index * 2, charBuffer, charPos * 2, num * 2);
839 for (
int i = 0; i < coreNewLine.Length; i++)
841 if (charPos == charLen)
843 await _this.FlushAsyncInternal(flushStream:
false, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
846 charBuffer[charPos] = coreNewLine[i];
852 await _this.FlushAsyncInternal(flushStream:
true, flushEncoder:
false, charBuffer, charPos).
ConfigureAwait(continueOnCapturedContext:
false);
855 _this.CharPos_Prop = charPos;
863 [__DynamicallyInvokable]
864 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
869 return base.WriteLineAsync();
873 __Error.WriterClosed();
875 CheckAsyncTaskInProgress();
876 return _asyncWriteTask = WriteAsyncInternal(
this,
null, 0, 0, charBuffer, charPos, charLen,
CoreNewLine, autoFlush, appendNewLine:
true);
885 [__DynamicallyInvokable]
886 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
891 return base.WriteLineAsync(value);
895 __Error.WriterClosed();
897 CheckAsyncTaskInProgress();
898 return _asyncWriteTask = WriteAsyncInternal(
this, value, charBuffer, charPos, charLen,
CoreNewLine, autoFlush, appendNewLine:
true);
907 [__DynamicallyInvokable]
908 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
913 return base.WriteLineAsync(value);
917 __Error.WriterClosed();
919 CheckAsyncTaskInProgress();
920 return _asyncWriteTask = WriteAsyncInternal(
this, value, charBuffer, charPos, charLen,
CoreNewLine, autoFlush, appendNewLine:
true);
936 [__DynamicallyInvokable]
937 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
952 if (buffer.Length - index < count)
958 return base.WriteLineAsync(buffer, index, count);
962 __Error.WriterClosed();
964 CheckAsyncTaskInProgress();
965 return _asyncWriteTask = WriteAsyncInternal(
this, buffer, index, count, charBuffer, charPos, charLen,
CoreNewLine, autoFlush, appendNewLine:
true);
972 [__DynamicallyInvokable]
973 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
978 return base.FlushAsync();
982 __Error.WriterClosed();
984 CheckAsyncTaskInProgress();
985 return _asyncWriteTask = FlushAsyncInternal(flushStream:
true, flushEncoder:
true, charBuffer, charPos);
988 private Task FlushAsyncInternal(
bool flushStream,
bool flushEncoder,
char[] sCharBuffer,
int sCharPos)
990 if (sCharPos == 0 && !flushStream && !flushEncoder)
994 Task result = FlushAsyncInternal(
this, flushStream, flushEncoder, sCharBuffer, sCharPos, haveWrittenPreamble, encoding, encoder, byteBuffer, stream);
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)
1001 if (!haveWrittenPreamble)
1003 _this.HaveWrittenPreamble_Prop =
true;
1005 if (preamble.Length != 0)
1007 await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(continueOnCapturedContext:
false);
1010 int bytes = encoder.
GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
1013 await stream.WriteAsync(byteBuffer, 0, bytes).ConfigureAwait(continueOnCapturedContext:
false);
1017 await stream.FlushAsync().ConfigureAwait(continueOnCapturedContext:
false);
Represents a character encoding.To browse the .NET Framework source code for this type,...
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.
Converts a set of characters into a sequence of bytes.
FileOptions
Represents advanced options for creating a T:System.IO.FileStream object.
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...
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.
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
abstract bool CanSeek
When overridden in a derived class, gets a value indicating whether the current stream supports seeki...
FileMode
Specifies how the operating system should open a file.
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...
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.
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....
Provides information about, and means to manipulate, the current environment and platform....
virtual void Close()
Closes the current stream and releases any resources (such as sockets and file handles) associated wi...
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.
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.
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
Represents a writer that can write a sequential series of characters. This class is abstract.
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.
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.
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.
Controls the system garbage collector, a service that automatically reclaims unused memory.
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.
FileAccess
Defines constants for read, write, or read/write access to a file.
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.
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.
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...
Represents an asynchronous operation that can return a value.
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Creates and controls a thread, sets its priority, and gets its status.