C#. Text files. The solution of problems on the modification of text files. Classes File, StreamReader, StreamWriter

Text files. The solution of tasks on the modification of text files. Classes File, StreamReader, StreamWriter

This topic provides examples of solving the most common tasks that arise when processing text files in C#. Examples are provided for applications built using the Console Application template. The solution to each problem is represented by the corresponding static function. Optionally, you can modify the demonstrated static functions in the class instance function.

To process text files, the operation of the File, StreamReader, and StreamWriter classes has been demonstrated.



Contents


Search other websites:

1. How to determine if the data in a text file has run out?

Reading data from a text file is carried out using the ReadLine() method. The method reads a string of characters from the current stream and returns it as a string. A line terminator is the character ‘\n’ in the file stream. If the end of the file is reached, the ReadLine() method returns null. An appropriate check in the program allows you to determine whether all data is read from a text file.

 

2. The sequence of actions when reading data from a file. Using the StreamReader class

To read data from a text file, you need to perform approximately the following sequence of actions:

1. Include the System.IO module using the string

using System.IO;

2. Create an instance of the StreamReader class using one of the overloaded constructors. At the same time as creating the instance, the file is opened for reading or writing. The StreamReader class has several constructors.

In the following example, a text file with the name “TextFile1.txt” is opened. The file is opened for reading (by default).

// Open text file for reading
StreamReader fileObj = new StreamReader("TextFile1.txt");

3. Using StreamReader instance implement cyclical reading lines of the file as shown below

...

// read one line
string s = fileObj.ReadLine();

while (s != null) // null value - end of file
{
  // Perform actions on string s
  // ...

  // Read next line
  s = fileObj.ReadLine();
}

...

4. Close the file using method Close()

fileObj.Close()

 

3. Function PrintFile(). Display the contents of the text file on the screen. Method 1

For a visual demonstration of reading information from a text file, the static PrintFile() function is provided, which displays the contents of the text file on the screen. To read lines from a file, the function uses the ReadLine() method of the StreamReader class. If the end of the file is reached, then ReadLine() returns null.

using System;
using static System.Console;

// To work with files you need to include the IO module
using System.IO;

namespace ConsoleApp7
{
  class Program
  {
    // A static function that displays the contents of a file on the screen.
    // The function uses the ReadLine() method to read a line from a file.
    // The file name is specified by the input parameter.
    // If the file is successfully read, then the function returns true.
    static bool PrintFile(string filename)
    {
      // 1. Create an instance of StreamReader class.
      // The StreamReader class is designed to read character data from a stream,
      // used to read information from text files.
      StreamReader sr;

      // 2. Open text file for reading
      try
      {
        // Attempt to open file for reading (default)
        sr = new StreamReader(filename);
      }
      catch (FileNotFoundException e)
      {
        // If the attempt is unsuccessful, then display
        // the appropriate message and exit
        WriteLine("Error: {0}", e.Message);
        return false;
      }

      // 3. The cycle of reading the lines of the file and displaying them on the screen
      string s; // additional variable

      WriteLine("The content of file {0}:", filename);

      s = sr.ReadLine(); // read first line from the file
      while (s != null) // end of file - the null value
      {
        // Display line on the screen
        WriteLine(s);

        // Read next line
        s = sr.ReadLine();
      }

      // 4. Close the file
      sr.Close();

      // 5. Return the result
      return true;
    }

    static void Main(string[] args)
    {
      // Вывести содержимое файла "TextFile1.txt" на экран
      PrintFile("TextFile1.txt");
      ReadLine();
    }
  }
}

 

4. Function PrintFile2(). Display the contents of the text file on the screen. Method 2

The following is an example of the static function PrintFile2(), which uses the ReadToEnd() method of the StreamReader class to read lines from a file. Unlike ReadLine(), the ReadToEnd() method reads all lines from a file and writes them to a string of type string inclusive with the characters ‘\n’, ‘\r’.

The algorithm is as follows:

  • first, all lines from the file are read into one line of type string;
  • for the received string, the Split() function is called, which splits the string into an array of strings. The sign of a line break is the character ‘\ n’;
  • display an array of strings on the screen.

 

using System;
using static System.Console;

// To work with files you need to include the IO module
using System.IO;

namespace ConsoleApp7
{
  class Program
  {
    // Display the content of a text file on the screen.
    // Function uses ReadToEnd() method.
    static bool PrintFile2(string filename)
    {
      // 1. Create an instance of StreamReader class.
      // The StreamReader class is designed to read character data from a stream,
      // used to read information from text files.
      StreamReader sr;

      // 2. Open text file for reading
      try
      {
        // Attempt to open file for reading (default)
        sr = new StreamReader(filename);
      }
      catch (FileNotFoundException e)
      {
        // If the attempt is unsuccessful, then display the appropriate message
        // and shut down the function
        WriteLine("Error: {0}", e.Message);
        return false;
      }

      // 3. Read lines from a file into one line of type string
      string s = sr.ReadToEnd();

      // 4. Convert lines from a file to an array of type string[]
      string[] lines = s.Split('\n'); // символ-разделитель - '\n'

      // 5. Display the array of lines on the screen
      for (int i = 0; i < lines.Length; i++)
        WriteLine("{0}", lines[i]);

      // 5. Close the file
      sr.Close();

      // 6. Return the result
      return true;
    }

    static void Main(string[] args)
    {
      // Display the content of the "TextFile1.txt" file
      PrintFile2("TextFile1.txt");
      Console.ReadLine();
    }
  }
}

 

5. Function ReplaceStringInFile(). Replacing a string in a text file. Using the features of the File class

When dealing with files, it is important to adhere to the correct read/write sequence. If you try to modify the data in the file directly, you can make many subtle mistakes. Therefore, it is recommended to use the following algorithm to replace a line in a text file:

  • read all the lines from the file to the array. The example uses the ReadAllLines() method of the static File class to read lines from a file. This method returns an array of type string[];
  • replace the string in the array;
  • write the lines from the array again to the file. The WriteAllLines() method of the File static class is used for writing. The file name and an array of strings of the type string[] to be written are passed to the method.

The text of the demo console application is as follows.

using System;
using static System.Console;

// To work with files you need to include the IO module
using System.IO;

namespace ConsoleApp7
{
  class Program
  {
    // Function replacing a line in a text file.
    // Parameters:
    // - filename - the name of the file;
    // - position - position in which you want to replace the line (numbered from 0);
    // - str - the replacement string.
    // The function returns true if the replacement of the line in the file was successful.
    static bool ReplaceStringInFile(string filename, int position, string str)
    {
      // 1. Verify that file exists.
      // Is used static function Exists().
      if (!File.Exists(filename)) return false;

      // 2. Get data from a file as an array of strings.
      // To do this, use the ReadAllLines () method.
      string[] arrayS = File.ReadAllLines(filename);

      // 3. Check if row position value is correct
      if ((position < 0) || (position >= arrayS.Length))
        return false;

      // 4. Replace the string
      arrayS[position] = str;

      // 5. Write the array of strings to the file
      File.WriteAllLines(filename, arrayS);

      // 6. Return the result
      return true;
    }

    static void Main(string[] args)
    {
      // Replacing a line in a file
      // 1. Declare variables
      string str;
      int pos;

      // 2. Enter the input data
      Console.WriteLine("Enter string:");
      str = Console.ReadLine();
      Console.WriteLine("Enter position:");
      pos = Convert.ToInt32(Console.ReadLine());

      // 3. Using ReplaceStringInFile() function
      if (ReplaceStringInFile("TextFile1.txt", pos, str))
        Console.WriteLine("Ok!");
      else
        Console.WriteLine("Error.");

      ReadLine();
    }
  }
}

 

6. Function RemoveStringFromFile(). Removing a line from a file by index. Example

When manipulating files that change the total number of lines in a file (insert, delete), it is best to present the read information in the form of lists of the List<string> type. This is due to the fact that it is more convenient to insert (delete) items into lists. The list does not require allocation of additional (often large) arrays of information, unlike an array. This example demonstrates the use of the ReadLine() function of the StreamReader class. When reading a line from a file, this function deletes the characters ‘\r’, ‘n’, which require additional processing.

using System;
using static System.Console;

// To work with files you need to include the IO module
using System.IO;

// To use the list of type List<string> you need to include Generic module
using System.Collections.Generic;

namespace ConsoleApp7
{
  class Program
  {
    // A function that implements the removal of a line from a file by its index.
    // Parametes:
    // - filename - the name of file;
    // - index - the position of the line to be deleted (numbered from 0).
    // If the deletion is successful, the function returns true.
    static bool RemoveLineFromFileByIndex(string filename, int index)
    {
      // 1. Declare a file variable
      StreamReader sr;

      // 2. Attempt to open the file
      try
      {
        // Use the OpenText() method of File class
        sr = File.OpenText(filename);
      }
      catch(FileNotFoundException e)
      {
        // If the file is not found, then handle the exception
        WriteLine(e.Message);
        return false;
      }

      // 3. Read all lines from file to list of lines lst
      List<string> lst = new List<string>(0); // create an empty list
      string s;
      while ((s = sr.ReadLine()) != null)
      lst.Add(s); // add line to the string

      // 4. The file is no longer needed, so you can close it
      sr.Close();

      // 5. Checking if index is correct
      if ((index < 0) || (index >= lst.Count))
        return false;

      // 6. Remove string from list in index position
      lst.RemoveAt(index);

      // 7. Write the lst list back to the file. For this
      // you need use the capabilities of the StreamWriter class.
      // Create an instance of class StreamWriter
      StreamWriter sw = new StreamWriter(filename); // open file for writing

      // Write list to the file
      for (int i = 0; i < lst.Count; i++)
        sw.WriteLine(lst[i]);

      // 8. Close the file
      sw.Close();

      // 9. Return the result
      return true;
    }

    static void Main(string[] args)
    {
      // Delete string to the file
      // 1. Declare variables
      int index;

      // 2. Input data
      WriteLine("Enter position:");
      index = Convert.ToInt32(Console.ReadLine());

      // 3. Use the function RemoveLineFromFileByIndex()
      if (RemoveLineFromFileByIndex("TextFile1.txt", index))
        WriteLine("Ok!");
      else
        WriteLine("Error.");

      ReadLine();
    }
  }
}

 

7. Function InsertLineInFile(). Insert a line into a file at a given position

Following the example of paragraph 6, you can implement the insertion of a line into a file at a given position. Lines in the file are pre-copied to a list of type List<string>. Using lists in such tasks facilitates the work of the programmer, since lists contain all the necessary methods for inserting, adding, deleting an element.
The proposed InsertLineInFile() function has one feature. If the insertion position (numbered from 0) is equal to the number of elements in file n, then the insertion line is added to the end of the file. Thus, the function implements the insertion and addition of a line to the file.

// A function that implements the insertion of a line into a file at a given position
// Parameters:
// - filename - the name of file;
// - pos - insertion position;
// - str - string to be inserted.
// The function returns true if the insert is successful.
static bool InsertLineInFile(string filename, int position, string str)
{
  // 1. Declare a file variable
  StreamReader sr;

  // 2. Attempting to open the file
  try
  {
    // Use the constructor of the StreamReader class
    sr = new StreamReader(filename);
  }
  catch (FileNotFoundException e)
  {
    // If the file is not found, then handle the exception
    WriteLine(e.Message);
    return false;
  }

  // 3. Read all lines from file to list of lines lst
  List<string> lst = new List<string>(0); // create empty list
  string s;
  while ((s = sr.ReadLine()) != null)
    lst.Add(s); // add string to list

  // 4. The file is no longer needed, so you can close it
  sr.Close();

  // 5. Check if position is correct
  if ((position < 0) || (position > lst.Count))
    return false;

  // 6. Implement the insert in the list
  // If position is equal to the number of lines in the lst list,
  // add a line to the end of the list
  if (position == lst.Count)
    lst.Add(str);
  else
    lst.Insert(position, str);

  // 7. Write list back to file
  // 7.1. Create an instance of class StreamWriter
  StreamWriter sw = new StreamWriter(filename);

  // 7.2. The cycle of writing a list to a file
  foreach (string ts in lst)
    sw.WriteLine(ts);

  // 7.3. Close the file
  sw.Close();

  // 8. Return the result
  return true;
}

 

8. Function ConvertLinesFileToList(). Convert file lines to List<string>

In points 6, 7, the code is repeated that forms a list of type List<string> from the lines of the file. Therefore, it is advisable to write the ConvertLinesFileToList() function, which implements the conversion of file lines to a list. The function text is as follows.

// A function that converts the lines of a file to a List<string>
// Parameters:
// - filename - the name of the file;
// - LS - list of lines that are obtained by reading from a file.
// If the conversion is successful, the function returns true.
static bool ConvertLinesFileToList(string filename, out List<string> LS)
{
  // 1. Declare a file variable
  StreamReader sr;

  // 2. Open the file
  try
  {
    // Attempting to open the file for reading
    sr = new StreamReader(filename);
  }
  catch(FileNotFoundException e)
  {
    // If the file is not found, then handle the exception
    WriteLine(e.Message);
    LS = null;
    return false;
  }

  // 3. Read file lines to LS list
  LS = new List<string>(0);
  string s;

  // loop reading lines from a file and creating a list
  while ((s = sr.ReadLine()) != null)
    LS.Add(s);

  // 4. Close the file
  sr.Close();

  // 5. Return the result
  return true;
}

 

9. Function AddArrayLinesInFile(). Adding an array of strings to the end of the file

The example shows a function that adds an array of strings to the end of a file. This function uses the ConvertLinesFileToList() function, which returns the lines of a file as a list and is described in paragraph 8. To work with files, the capabilities of the StreamReader and StreamWriter classes are used.

The algorithm of the method is as follows:

  • read data from a file into a list of type List<string>;
  • add an array of strings to the list;
  • write the modified list to a file. To write a list, the StreamWriter class tools are used.

The program code for the AddArrayLinesInFile() function is as follows.

using static System.Console;

// To work with files you need to include the IO module
using System.IO;

// To use the List<string> list, you need to include the Generic module
using System.Collections.Generic;

...

// A function that adds an array of strings to the end of the file.
// Parameters:
// - filename - the name of the file;
// - arrayS - array of lines that are added to the end of the file.
static bool AddArrayLinesInFile(string filename, string[] arrayS)
{
  // 1. Get a list of file lines
  List<string> lst;

  // invoke the function from paragraph 8
  if (!ConvertLinesFileToList(filename, out lst))
  {
    return false;
  }

  // 2. Add array of strings to lst list
  foreach (string s in arrayS)
    lst.Add(s);

  // 3. Write list to the file
  // 3.1. Create an instance of the StreamWriter class
  StreamWriter sw = new StreamWriter(filename);

  // 3.2. The cycle of writing a list to a file
  foreach (string ts in lst)
    sw.WriteLine(ts);

  // 3.3. Close the file
  sw.Close();

  // 4. Return the result
  return true;
}

Using a function in other program code may be, for example, like this.

static void Main(string[] args)
{
  // Adding an array of strings to the end of the file
  // 1. Array of strings
  string[] arrS = { "abcd", "jklmn", "oprst" };

  // 2. Using the function AddArrayLinesInFile()
  if (AddArrayLinesInFile("TextFile1.txt", arrS))
    WriteLine("Ok!");
  else
    WriteLine("Error.");

  ReadLine();
}

 

10. Function SwapLinesInFile(). Swapping two lines in the file

Swapping two lines in a file does not change the total number of lines. Therefore, it is advisable to represent the read lines from the file as an array of type string[].

In C#, in the static class File, there is a useful function ReadAllLines(), which returns the lines of a file as an array of string[]. As with the ReadLine() function of the StreamReader class, each line in the ReadAllLines() function does not contain the characters ‘\n’ and ‘\r’.

The static File file also contains the WriteAllLines() function, which writes strings of type string[] to the file.

The following is a snippet of code that contains a description of the SwapLinesInFile() function.

using static System.Console;

// To work with files you need to include the IO module
using System.IO;
using System;

...

// Function swapping two lines in a file
// Parameters:
// - filename - the name of the file
// - pos1, pos2 - positions of lines (numbered from 0).
// The function returns true if the string swap was successful.
static bool SwapLinesInFile(string filename, int pos1, int pos2)
{
  // 1. Checking whether a file exists
  if (!File.Exists(filename)) return false;

  // 2. Read all lines from file to arrayS array
  string[] arrayS = File.ReadAllLines(filename);

  // 3. Check if pos1, pos2 are correct
  if ((pos1 < 0) || (pos1 >= arrayS.Length)) return false;
  if ((pos2 < 0) || (pos2 >= arrayS.Length)) return false;

  // 4. Swap strings in arrayS
  string s = arrayS[pos1];
  arrayS[pos1] = arrayS[pos2];
  arrayS[pos2] = s;

  // 5. Write modified arrayS array back to file
  File.WriteAllLines(filename, arrayS);

  // 6. Return the result
  return true;
}

Using the SwapLinesInFile() function in other code can be, for example,

static void Main(string[] args)
{
  // Swapping two lines in the file
  // 1. Input positions of lines
  int pos1, pos2;

  Write("pos1 = ");
  pos1 = Int32.Parse(ReadLine());
  Write("pos2 = ");
  pos2 = Int32.Parse(ReadLine());

  // 2. Using the function
  if (SwapLinesInFile("TextFile1.txt", pos1, pos2))
    WriteLine("Ok!");
  else
    WriteLine("Error.");

  ReadLine();
}

 

11. Function ReverseStringsInFile(). Reversing file lines (get file lines in reverse order)

The function algorithm is as follows:

  • read file lines into an array of type string[] using the File.ReadAllLines() function;
  • using a loop reverse an array of strings;
  • write the reversed lines back to the file.

The text of the function ReverseStringsInFile() is as follows

// To work with files you need to include the IO module
using System.IO;

// A function that reverses the order of lines in a file.
// The function returns true if the reversal is successful.
static bool ReverseAllLinesInFile(string filename)
{
  // 1. Checking whether a file exists
  if (!File.Exists(filename)) return false;

  // 2. Read all lines from file to arrayS array
  string[] arrayS = File.ReadAllLines(filename);
  string s;

  // 3. Reverse lines in arrayS
  for (int i = 0; i < arrayS.Length / 2; i++)
  {
    s = arrayS[i];
    arrayS[i] = arrayS[arrayS.Length - i - 1];
    arrayS[arrayS.Length - i - 1] = s;
  }

  // 4. Write modified arrayS array back to file
  File.WriteAllLines(filename, arrayS);

  // 5. Return the result
  return true;
}

Using a function can be, for example,

static void Main(string[] args)
{
  // Reversing lines in a file
  if (ReverseAllLinesInFile("TextFile1.txt"))
    WriteLine("Ok!");
  else
    WriteLine("Error.");

  ReadLine();
}

 

12. Function SortLineInFileBubble(). Sorting lines in a file using the bubble method

 

using static System.Console;

// To work with files you need to include the IO module
using System.IO;

...

// A function that sorts lines in a file using the bubble method.
// Function, returns true if the sort is successful
static bool SortAllLinesInFileBubble(string filename)
{
  // 1. Check, if the file exists
  if (!File.Exists(filename)) return false;

  // 2. Read all lines from file to arrayS array
  string[] arrayS = File.ReadAllLines(filename);
  string s;

  // 3. Sort strings in arrayS using bubble method
  for (int i = 0; i < arrayS.Length; i++)
    for (int j = arrayS.Length - 1; j > i; j--)
      if (arrayS[j - 1].CompareTo(arrayS[j]) > 0) // Sort Ascending
      {
        s = arrayS[j - 1];
        arrayS[j - 1] = arrayS[j];
        arrayS[j] = s;
      }

  // 4. Write modified arrayS array back to file
  File.WriteAllLines(filename, arrayS);

  // 5. Return the result
  return true;
}

Using the SortAllLinesInFileBubble() function in the main() function

static void Main(string[] args)
{
  // Sort lines in the file
  if (SortAllLinesInFileBubble("TextFile1.txt"))
    WriteLine("Ok!");
  else
    WriteLine("Error.");

  ReadLine();
}

 


Related topics

 


 

0
fb-share-icon20