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.

advertisement
advertisement

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

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.