C#. StreamWriter class. Purpose. Constructors




StreamWriter class. Purpose. Constructors. Create an output stream in different ways

This topic is related to the topic:


Contents


Search other websites:

1. Class StreamWriter. The purpose

The StreamWriter class is designed to write to a stream of character data. This class is inherited from the abstract TextWriter class and implements some of its methods. Figure 1 shows a list of the main methods that the StreamWriter class inherits.

C#. A list of the main methods and properties that the StreamWriter class inherits from the TextWriter class

Figure 1. A list of the main methods and properties that the StreamWriter class inherits from the TextWriter class

For more information on declaring and using methods of the StreamWriter class, see the next topic.

 

2. Constructors for the StreamWriter class. Creating a stream associated with a text file

The StreamWriter class contains a significant number of constructors for creating an output stream in a variety of ways.

2.1. Constructors that create an output stream based on a file path

 

public StreamWriter(string path)
public StreamWriter(string path, bool append)
public StreamWriter(string path, bool append, System.Text.Encoding encoding)
public StreamWriter(string path, bool append, System.Text.Encoding encoding, int bufferSize)

here

  • path – path to the file, for example “C:\\1\\myfile.txt”;
  • append – a flag that determines the ability to append data to the end of the file. If append = true, then data is appended to the end of the file. Otherwise, the data is overwritten;
  • encoding – character encoding;
  • bufferSize – the size of the buffer to write to the file. The file is written in portions of the bufferSize size.

When using constructors, the following types of exceptions may be thrown:

  • System.UnautorizedAccessException thrown when access is denied;
  • System.ArgumentException – thrown when path is empty or contains the name of a system device (for example, com1, com2, lpt1, etc.);
  • System.ArgumentNullException – thrown when path = null;
  • System.IO.DirectoryNotFoundException – thrown when path is incorrectly defined;
  • System.IO.IOException – path includes invalid syntax for file name, folder name, or volume label;
  • System.IO.PathTooLongException – thrown when the path and/or file name exceeds the system-defined maximum length;
  • System.Security.SecurityException – thrown when the calling thread does not have the required permission.

Example.

// Include namespaces System, System.IO
using System;
using System.IO;

...

try
{
  // Creating different file streams
  // 1. The stream associated with the file "file1.txt"
  StreamWriter fOut1 = new StreamWriter("file1.txt");

  // 2. The stream associated with the file "file2.txt"
  StreamWriter fOut2 = new StreamWriter("file2.txt", false);

  // 3. The stream associated with the file "file1.txt"
  StreamWriter fOut3 = new StreamWriter("file3.txt", false, System.Text.Encoding.UTF8);

  // 4. The stream associated with the file "file1.txt"
  StreamWriter fOut4 = new StreamWriter("file4.txt", false, System.Text.Encoding.ASCII, 1024);

  // Performing actions in threads
  // ...

  // Close streams
  fOut1.Close();
  fOut2.Close();
  fOut3.Close();
  fOut4.Close();
}
catch (UnauthorizedAccessException e)
{
  Console.WriteLine("UnauthorizedException");
}
catch (ArgumentException e)
{
  Console.WriteLine("Agrument error.");
}
catch (DirectoryNotFoundException e)
{
  Console.WriteLine("Directory not found.");
}
catch (IOException e)
{
  Console.WriteLine("Input/output error.");
}
catch(System.Security.SecurityException e)
{
  Console.WriteLine("Security error.");
}

...

 

2.2. Constructors that create a file output stream from another stream

On the basis of another stream of type Stream, you can create an output stream of type StreamReader. For this, the following constructors are used:

public StreamWriter(System.IO.Stream stream)
public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding)
public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize)
public StreamWriter(System.IO.Stream stream, [System.Text.Encoding encoding = null], [int bufferSize = -1], [bool leaveOpen = False])

here

  • stream is a stream of type Stream. The Stream class is the base class for all stream classes;
  • encoding – encoding system;
  • bufferSize – buffer size in bytes;
  • leaveOpen – if leaveOpen = true, then the stream remains open after the StreamWriter is deleted, otherwise leaveOpen = false.

Example.

// Include namespace System, System.IO
using System;
using System.IO;

...

try
{
  // Creating file streams from other streams

  // 1. Link with "file1.txt" file in UTF-8 encoding
  FileStream fs1 = new FileStream("file1.txt", FileMode.Open, FileAccess.Write);
  StreamWriter fOut1 = new StreamWriter(fs1, System.Text.Encoding.UTF8);

  // 2. The stream associated with the file "file2.txt"
  FileStream fs2 = new FileStream("file2.txt", FileMode.Open, FileAccess.Write);
  StreamWriter fOut2 = new StreamWriter(fs2);

  // Performing actions in threads
  // ...

  // Close streams
  fOut1.Close();
  fOut2.Close();
}
catch (System.Exception e)
{
  Console.WriteLine(e.Message);
}

...

 

3. Using the using() statement to create an output stream

In order not to dismiss the resources allocated for the file stream, you can use the using() statement. This operator allows you to release these resources automatically.

Example. The example creates multiple streams using the using() statement.

// Include namespaces System, System.IO
using System;
using System.IO;

...

// Create file streams from other streams using the using() statement
using (FileStream fs1 = new FileStream("file1.txt", FileMode.Open, FileAccess.Write),
  fs2 = new FileStream("file2.txt", FileMode.Open, FileAccess.Write))
{
  using (StreamWriter fOut1 = new StreamWriter(fs1, System.Text.Encoding.UTF8),
  fOut2 = new StreamWriter(fs2))
  {
    // Performing actions in streams
    // ...
  }
}

...

 

4. An example of creating a file with zero length using StreamWriter. Easiest way to use the constructor

To create a file with zero length (no data) using the StreamWriter class, just write the following code

...

// Include System.IO namespace
using System.IO;

...

// Declare an instance of the StreamWriter class
StreamWriter fOut = new StreamWriter("myfile1.txt");

// Close the stream
fOut.Close();

...

In the example above, a file named myfile1.txt is created in the current (relative to the executable file) directory.

 


Related topics