File I/O in C# Language
File Input/Output (I/O) is a fundamental aspect of any programming language, including
File Input/Output (I/O) is a fundamental aspect of any programming language, including
To read data from a file in C#, you can use the File and StreamReader classes. Here’s an example of how to read text from a file:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (IOException e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
In this example, we use a StreamReader to open and read from the file “example.txt” line by line.
To write data to a file, you can use the File and StreamWriter classes. Here’s an example of how to write text to a file:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "output.txt";
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Hello, World!");
writer.WriteLine("This is a sample text.");
}
Console.WriteLine("Data has been written to the file.");
}
catch (IOException e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
In this example, we create a StreamWriter to write text to the file “output.txt.”
You can check if a file exists using the File.Exists method. Here’s an example:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
if (File.Exists(filePath))
{
Console.WriteLine("File exists!");
}
else
{
Console.WriteLine("File does not exist.");
}
}
}
This code checks if the file “example.txt” exists in the current directory.
C# provides a wide range of file I/O operations beyond basic reading and writing, including file copying, moving, deleting, and more. These operations can be performed using classes such as File, Directory, and Path from the System.IO namespace.
Subscribe to get the latest posts sent to your email.