C#. Class StreamWriter. Overview of methods and properties




Class StreamWriter. Overview of methods and properties

This topic is a continuation of the topic:


Contents


Search other websites:

1. Methods of StreamWriter class

In the examples below, in order to use the methods of the StreamWriter class correctly, you need to include the System and System.IO namespaces.

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

 

1.1. Method Close(). Closing the output stream

The Close() method is designed to close the output stream and release resources. Method declaration is as follows

public override void Close();

Example.

// Create StreamWriter stream
StreamWriter fOut = new StreamWriter("myfile2.txt");

// Use the stream
// ...

// Close the stream
fOut.Close();

 

1.2. Method Flush(). Clearing buffers

The Flush() method is used to flush all buffers for the current thread. The method declaration is as follows:

public override void Flush();

When using the method, exceptions of the following types can be thrown:

  • System.ObjectDisposedException – the current output stream is closed;
  • System.IO.IOException – I/O error;
  • System.Text.EncoderFallBackException – the current encoding does not support displaying half of a Unicode surrogate pair.

Example.

// Create a StreamWriter instance
StreamWriter fOut = new StreamWriter("myfile2.txt");

// Clear the buffer
fOut.Flush();

// Using a stream
// ...

 

1.3. Methods for writing to a file data stream, which are represented by individual characters

The StreamWriter class provides a whole set of overloaded Write() or WriteLine() methods for writing text information to a file stream in a variety of ways.

1.3.1. Method Write(char). Single character writing

This method allows writing character by character to the file stream

public override void Write(char value);

where value is the value to write.

When using the method, there may be exceptions of the following types

  • System.IO.IOException – input/output error;
  • System.ObjectDisposedException – thrown when the AutoFlush property is set to true or the StreamWriter buffer is full and the output stream is closed.
  • System.NonSupportedException – Thrown when the AutoFlush property is true or the StreamWriter buffer is full and the contents of the buffer can be written to a fixed-size underlying stream.

Example. In the example, a string entered from the keyboard is written to the file, character by character.

...

using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
{
  // Enter a string from the keyboard
  string s;
  Console.WriteLine("Enter string:");
  s = Console.ReadLine();

  // Split string s into an array of type char[]
  char[] array = s.ToCharArray();

  // Write character by character to fOut stream
  foreach (char c in array)
    fOut.Write(c);
}

...

 

1.3.2. Method Write(char[]). Writing an array of characters

To write a char[] array to a file, use the Write() method followed by a declaration

public override void Write(char[] buffer);

here

  • buffer is a character array containing data to be written. If buffer is null, then nothing is written.

When using the Write() method, the following types of exceptions are possible:

  • System.IO.IOException – I/O error;
  • System.ObjectDisposedException – thrown when the AutoFlush property is set to true or the StreamWriter buffer is full and the output stream is private;
  • System.NonSupportedException – Thrown when the AutoFlush property is true or the StreamWriter buffer is full and the contents of the buffer can be written to a fixed-size underlying stream.

Example. In the example, an array of strings of type string[] is written to the file. A newline character is written after each line using the WriteLine() method.

...

using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
{
  // Original array of strings
  string[] AS = { "line - 1", "line - 2", "line - 3" };
  char[] buffer;

  // Cycle of writing an AS array to a file
  for (int i = 0; i < AS.Length; i++)
  {
    // convert string to char[]
    buffer = AS[i].ToCharArray();

    // write buffer to file
    fOut.Write(buffer);

    // new line
    fOut.WriteLine();
  }
}

...

 

1.3.3. Method Write(char[], int, int). Writing a character array with a range

This method is used to write a substring of characters to a stream. Method declaration is as follows:

public override void Write(char[] buffer, int index, int count);

here

  • buffer – an array of characters containing data to be written;
  • index – character position in the buffer from which data reading starts;
  • count – the maximum number of characters that can be written.

When using the method, exceptions of the following types can be thrown:

  • System.ArgumentNullException – the case when the value of buffer = null;
  • System.ArgumentException – thrown if the count value is greater than the value of the buffer length minus index;
  • System.ArgumentOutOfRangeException – index or count is negative;
  • System.IO.IOException – an input/output error is generated;
  • System.ObjectDisposedException – thrown when the AutoFlush property is set to true or the StreamWriter buffer is full and the output stream is closed;
  • System.NonSupportedException – thrown when the AutoFlush property is true or the StreamWriter buffer is full and the contents of the buffer can be written to a fixed-size underlying stream.

Example. In the example, the first 5 characters of an array of strings of type string[] are written to the file. All other characters are truncated.

using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
{
  // Original array of strings
  string[] AS = { "aldkfjasldj", "ladjkflaj", "iouweoiwe" };

  // buffer for representing string as char[]
  char[] buffer;

  // Cycle of writing an AS array to a file
  for (int i = 0; i < AS.Length; i++)
  {
    // convert string to char[]
    buffer = AS[i].ToCharArray();

    // write buffer to file
    fOut.Write(buffer, 0, 5); // write the first 5 characters

    // new line
    fOut.WriteLine();
  }
}

 

1.4. Methods for writing strings of type string to a stream
1.4.1. Methods Write(string) and WriteLine(string). Write a string

The Write() and WriteLine() methods with a string parameter are designed to write a string to a stream. Method declarations are as follows

public override void Write(string value);
public override void WriteLine(string value);

here value is the string that is written to the stream.

The WriteLine() method, unlike the Write() method, additionally writes a newline character to the stream.

When using the method, there may be exceptions of the following types:

  • System.IO.IOException – I/O error;
  • System.ObjectDisposedException – thrown when the AutoFlush property is set to true or the StreamWriter buffer is full and the output stream is private;
  • System.NonSupportedException – thrown when the AutoFlush property is true or the StreamWriter buffer is full and the contents of the buffer can be written to a fixed-size underlying stream.

Example. In the example, an array of strings of type string[] is written to the file. The WriteLine() method is used.

...

using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
{
  // Original array of strings
  string[] AS = {
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  };

  // Cycle of writing an AS array to a file
  for (int i = 0; i < AS.Length; i++)
  {
    // method WriteLine()
    fOut.WriteLine(AS[i]);
  }
}

...

 

1.4.2. The Write(string, object) and WriteLine(string, object) methods. Writing a formatted string with one argument to the stream

These methods allow you to write an object to a stream according to the string specifying the output format. Method declarations are as follows

public override void Write(string format, object arg0)
public override void WriteLine(string format, object arg0)

Example. A double-type number with precision 3 decimal places is written to the file.

static void Main(string[] args)
{
  using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
  {
    // Writing a double to a file with precision 3 decimal places
    fOut.Write("{0:f3}", Math.PI); // 3.142
  }
}

 

1.4.3. Methods Write(string, object, object) and WriteLine(string, object, object). Writing a formatted string with two arguments

 

public override void Write(string format, object arg0, object arg1);
public override void WriteLine(string format, object arg0, object arg1);

Example. Write two numbers to the file: an integer and a float.

using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
{
  // Writing an int and a float
  int d = 27;
  float x = 3.2309f;
  fOut.Write("{0} {1:f}", d, x); // 27 3.23
}

 

1.4.4. Methods Write(string, object, object, object) and WriteLine(string, object, object, object). Writing a formatted string with three arguments

 

public override void Write(string format, object arg0, object arg1, object arg2);
public override void WriteLine(string format, object arg0, object arg1, object arg2);

Example. Write three int numbers to the file.

using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
{
  // Writing three int numbers to a file
  int d1 = 88, d2 = 323, d3 = 15;
  fOut.Write("{0} {1} {2}", d1, d2, d3); // 88 323 15
}

 

1.4.5. Method Write(string, object[]). Writing a formatted string with any number of arguments

Method declarations that write any number of arbitrary arguments are as follows:

public override void Write(string format, params object[] arg);
public override void WriteLine(string format, params object[] arg);

Example. An array of coordinates of segments (x1, y1), (x2, y2) is given. You need to write these coordinates to the file.

using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
{
  // Writing an array of coordinates to a file
  int[,] Lines = {
    { 2, 5, 3, -1 },
    { 4, 7, 2, 9 },
    { -1, -3, 2, 8 }
  };

  // Loop for writing an array to a file
  for (int i = 0; i < Lines.Length / 4; i++)
  {
    fOut.WriteLine("x1 = {0}, y1 = {1}, x2 = {2}, y2 = {3}",
      Lines[i, 0], Lines[i, 1], Lines[i, 2], Lines[i, 3]);
  }
}

 

2. Properties
2.1. Property AutoFlush

Gets or sets a value indicating whether the StreamWriter instance flushes the buffer after each call to the Write(System.Char) method. Method declarations are as follows

public virtual bool AutoFlush { get; set; }

The true value causes the StreamWriter to flush its stream.

Example.

using (StreamWriter fOut = new StreamWriter("myfile2.txt"))
{
  // Instructions to clear the buffer
  fOut.AutoFlush = true;

  // some actions
  // ...
}

 

2.2. Property Encoding

The Encoding property is used to determine the encoding system.

public override System.Text.Encoding Encoding { get; }

The encoding system is set in the constructor when the current instance is created. If the encoding system is not explicitly specified, the default is

System.Text.UTF8Encoding.

Example.

// Writing in the ASCII encoding system
using (FileStream fs = new FileStream("myfile2.txt", FileMode.Open, FileAccess.Write))
{
  using (StreamWriter fOut = new StreamWriter(fs,
    System.Text.Encoding.ASCII))
  {
    // Write string to the file
    fOut.WriteLine("Hello world!");

    // Write also the current encoding system using the Encoding property
    string name = fOut.Encoding.BodyName;
    fOut.WriteLine(name);
  }
}

 


Related topics