Convert Strings to File in C#
Below is a simple C# program that provides how to convert a string to a file. The program uses the File.WriteAllText
method from the System.IO
namespace, making the process short.
using System;
using System.IO;
class Program
{
static void Main()
{
// The string to be converted to a file
string dataToWrite = "Hello, this is a sample string to be written to a file.";
// Specify the file path
string filePath = "output.txt";
try
{
// Convert the string to a file
File.WriteAllText(filePath, dataToWrite);
Console.WriteLine("String successfully converted to a file.");
// Read and display the content of the file
string readData = File.ReadAllText(filePath);
Console.WriteLine("Content of the file: \n" + readData);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
- We define a string (
dataToWrite
) that we want to convert to a file. - Specify the file path where the data will be stored (
filePath
). - Use the
File.WriteAllText
method to write the string to the specified file. - Read the content of the file using
File.ReadAllText
and display it.
Output:
String successfully converted to a file.
Content of the file:
Hello, this is a sample string to be written to a file.
Comments (0)