C# Program to Perform File Operations
Posted by Superadmin on August 13 2022 10:05:42

C# Program to Perform File Operations

 

 

This is a C# Program to perform text operations in a file.

Problem Description

This C# Program Performs Text Operations in a File.

Problem Solution

Here appending text, creating a new text operation are performed.

Program/Source Code

Here is source code of the C# Program to Perform Text Operations in a File. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Perform Text Operations in a File
 */
using System;
using System.IO;
class Program
{
    static void Main()
    {
        FileInfo finfo = new FileInfo("C:\\sri\\srip.txt");
        using (StreamWriter writer = finfo.AppendText())
        {
            writer.WriteLine("New File with various Text operations");
        }
        finfo = new FileInfo("C:\\sri\\srip.txt");
        using (StreamWriter writer = finfo.CreateText())
        {
            writer.WriteLine("New File with various Text operations");
        }
        using (StreamReader reader = finfo.OpenText())
        {
            Console.WriteLine(reader.ReadToEnd());
        }
        Console.Read();
    }
}
Program Explanation

This C# program is used to perform text operations in a file. Hence the AppendText() function is used to create a StreamWriter. It is used to append UTF-8 encoded text to an existing file or to a new file if the specified file does not exist.

Then CreateText() function is used to create or open a file for writing UTF-8 encoded text. The OpenText() function is used to open an existing UTF-8 encoded text file for reading. Here appending text, creating new text operations are performed and print the file text operations.

Runtime Test Cases
 
New File with various Text operations