Mohanapriya R Mohanapriya R
Updated date May 17, 2024
In this article, we will explore converting files to strings in C#. Follow along with a practical program, learn the step-by-step process, and output.

Convert File to Strings in C#.

Below is a simple C# program that shows how to convert the contents of a file to a string:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Specify the path to the file
        string filePath = "sample.txt";

        try
        {
            // Read the content of the file into a string
            string fileContent = File.ReadAllText(filePath);

            // Display the output
            Console.WriteLine("File Content as String:");
            Console.WriteLine(fileContent);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
  • We begin by importing the necessary namespaces, including System and System.IO, to leverage file-related functionality.
  • The Main method sets the path to the file (in this case, "sample.txt").
  • Inside a try-catch block, we use File.ReadAllText() to read the entire content of the file specified by filePath and store it in the fileContent variable.
  • Finally, we display the file content as a string using Console.WriteLine().

Output:

Assuming the file "sample.txt" contains the text "Hello, World!", the program output would be:

File Content as String:
Hello, World!

Comments (0)

There are no comments. Be the first to comment!!!