Stream writer is used to write characters to a stream in a particular encoding. By default, a StreamWriter is not thread safe and use an instance of UTF8Encoding. You can specify it if you want to.
Example
Example
string fileName = @"c:\text.txt";There are more exception you should use when you using StreamWriter
try
{
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
sw.WriteLine("Hello world");
sw.Close();
fs.Close();
}
}
catch (IOException)
{
MessageBox.Show("No enough disk space or drive is readonly");
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Access deny");
}
catch (SecurityException)
{
MessageBox.Show("You don't have enough required permission");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
| Exception Type | Condition |
|---|---|
| IOException | A general I/O exception occurred, such as trying to access a CD-ROM drive whose tray is open. |
| DirectoryNotFoundException | The directory information specified in path was not found. |
| UnauthorizedAccessException | Access is denied. The caller does not have the required permission. |
| ArgumentException | path is a zero-length string, contains only white space, or contains one or more implementation-specific invalid characters. |
| ArgumentNullException | path or encoding is null |
| NotSupportedException | path is in an implementation-specific invalid format. |
| PathTooLongException | The length of path or the absolute path information for path exceeds the implementation-specific maximum length. |
| SecurityException | The caller does not have the required permission. |
