See TextWriter.Synchronized for a thread-safe wrapper.įor a list of common I/O tasks, see Common I/O Tasks. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as StreamWriter(String, Boolean, Encoding) or StreamWriter.īy default, a StreamWriter is not thread safe. This behavior is different from the behavior provided by the encoding object in the Encoding.UTF8 property. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This instance of UTF8Encoding is constructed without a byte order mark (BOM), so its GetPreamble method returns an empty byte array. StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). To dispose of the type directly, call its Dispose method in a try/ catch block.
When you have finished using the type, you should dispose of it either directly or indirectly. This type implements the IDisposable interface. StreamWriter is designed for character output in a particular encoding, whereas classes derived from Stream are designed for byte input and output. Using sr As StreamReader = New StreamReader("CDriveDirs.txt") Using sw As StreamWriter = New StreamWriter("CDriveDirs.txt") ' Get the directories currently on the C drive.ĭim cDirs As DirectoryInfo() = New DirectoryInfo("c:\").GetDirectories() Using (StreamReader sr = new StreamReader("CDriveDirs.txt")) Read and show each line from the file. Using (StreamWriter sw = new StreamWriter("CDriveDirs.txt")) Get the directories currently on the C drive.ĭirectoryInfo cDirs = new Write each directory name to a file. The constructor used in this example is not supported for use in Windows Store Apps.
The using statement automatically calls Dispose on the object when the code that is using it has completed. A good practice is to use these objects in a using statement so that the unmanaged resources are correctly disposed.
The following example shows how to use a StreamWriter object to write a file that lists the directories on the C drive, and then uses a StreamReader object to read and display each directory name. SerializableAttribute ComVisibleAttribute Examples