Namespace: System.IO
StreamWriter
public class StreamWriter : TextWriter
Represents a text writer that provides a convenient way to write a sequence of strings or bytes to a stream.
Constructors
-
public StreamWriter( Stream stream )Initializes a new instance of the
StreamWriter
class for the specified stream, with the default encoding and buffer size. -
public StreamWriter( string path )Initializes a new instance of the
StreamWriter
class for the specified file path, with the default encoding and buffer size. If the file exists, it will be overwritten. -
public StreamWriter( string path, bool append )Initializes a new instance of the
StreamWriter
class for the specified file path and a Boolean value indicating whether to append data to the file. -
public StreamWriter( Stream stream, Encoding encoding )Initializes a new instance of the
StreamWriter
class for the specified stream and encoding, with the default buffer size. -
public StreamWriter( string path, bool append, Encoding encoding )Initializes a new instance of the
StreamWriter
class for the specified file path, append option, and encoding.
Methods
-
public override void Write( string value )Writes a string to the stream.
-
public override void WriteLine( string value )Writes a string followed by a line terminator to the stream.
-
public void Flush( )Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
-
protected override void Dispose( bool disposing )Releases the unmanaged resources used by the
StreamWriter
and optionally releases the managed resources.
Properties
-
public override Encoding { get; }Gets the
Encoding
in which the output is written. -
public override string NewLine { get; set; }Gets or sets a value indicating whether the
StreamWriter
will flush its buffer after a specific operation.
Example
using System.IO;
using System.Text;
public class Example
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
{
sw.WriteLine("This is the first line.");
sw.WriteLine("This is the second line.");
sw.Write("This is a continuation of the second line.");
sw.Write(" And this is another part.");
sw.WriteLine(); // Adds a blank line
sw.WriteLine("End of file.");
}
// Verify the content
Console.WriteLine($"Content written to {path}");
}
}