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
SystemandSystem.IO, to leverage file-related functionality. - The
Mainmethod 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 byfilePathand store it in thefileContentvariable. - 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)