C # text file reading and writing


Release date:2023-09-01 Update date:2023-10-13 Editor:admin View counts:217

Label:

C # text file reading and writing

StreamReader and StreamWriter class is used for data reading and writing to text files. These classes are derived from the abstract base class Stream inherit Stream supports byte reading and writing of file stream.

StreamReader class

StreamReader class inherits from the abstract base class TextReader indicating that the reader reads a series of characters

The following table lists some commonly used methods ithe StreamWriter class:

Serial number

Method & description

1

Public override void Close () closes the StreamReader object and the underlying stream and releases any system resources related to the reader.

2

Public override int Peek () returns the next available character, but does not use it.

3

Public override int Read () reads the next character from the input stream and moves the character position forward one character.

For a complete list of methods, please visit Microsoft’s C # documentation.

Example

The following example demonstrates reading a file named Jamaica.txt. The documents are as follows:

Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
using System;
using System.IO;

namespace FileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Create an instance of StreamReader to read files
                // Using statements can also close StreamReader
                using (StreamReader sr = new StreamReader("c:/jamaica.txt"))
                {
                    string line;

                    // Read and display lines from the file until the end of the file
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception e)
            {
                // Display error messages to users
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
    }
}

When you compile and execute the above program, it displays the contents of the file.

StreamWriter class

StreamWriter class inherits from abstract class TextWriter indicating that the writer writes a series of characters

The following table lists some commonly used methods ithe StreamWriter class:

Serial number

Method & description

1

Public override void Close () closes the current StreamWriter object and theunderlying stream.

2

Public override void Flush () cleans up all buffers of the current writer sothat all buffered data is written to the underlying stream.

3

Public virtual void Write (bool value) writes the text representation of a Boolean value to a text string or stream. (inherited from TextWriter. )

4

Public override void Write (char value) writes a character to the stream.

5

Public virtual void Write (decimal value) writes a text representation of a decimal value to a text string or stream.

6

Public virtual void Write (double value) writes a text representation of an 8-byte floating-point value to a text string or stream.

7

Public virtual void Write (int value) writes a text representation of a 4-byte signed integer to a text string or stream.

8

Public override void Write (string value) writes a string to the stream.

9

Public virtual void WriteLine () writes the line Terminator to a text stringor stream.

For a complete list of methods, please visit Microsoft’s C # documentation.

Example

The following example demonstrates the use of the StreamWriter class towrite text data to the file:

using System;
using System.IO;

namespace FileApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            string[] names = new string[] {"Zara Ali", "Nuha Ali"};
            using (StreamWriter sw = new StreamWriter("names.txt"))
            {
                foreach (string s in names)
                {
                    sw.WriteLine(s);

                }
            }

            // Read and display each line from the file
            string line = "";
            using (StreamReader sr = new StreamReader("names.txt"))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Zara Ali
Nuha Ali

Powered by TorCMS (https://github.com/bukun/TorCMS).