File is a static class that provides static methods that are used to create, delete, copy, move, and open a file from the disk. If you want to use File class, you need to import the System.IO
namespace.
Create a File:
The following example shows how to create and read a file using StreamWriter
& StreamReader
.
using System;
using System.IO; // Must add this namespace
namespace ConsoleApp
{
class DirectoryAndFile
{
static void Main(string[] args)
{
string str = string.Empty;
string filePath = @"E:\Samples\Employee.txt";
// Check whether the file is exist already
if (!File.Exists(filePath))
{
// Create a file and write names
using (StreamWriter sw = File.CreateText(filePath))
{
sw.WriteLine("John");
sw.WriteLine("Mathew");
sw.WriteLine("Peter");
sw.WriteLine("Marry");
sw.WriteLine("Luke");
}
}
// Open and Read the file contents
using (StreamReader streamReader = File.OpenText(filePath))
{
while ((str = streamReader.ReadLine()) != null)
{
Console.WriteLine(str);
}
Console.ReadKey();
}
}
}
}
Output:
Delete a File:
Use File.Delete() method to delete an existing file in disk using C#. Below code explains how to delete a file,
using System;
using System.IO; // Must add this namespace
namespace ConsoleApp
{
class DirectoryAndFile
{
static void Main(string[] args)
{
string filePath = @"E:\Samples\Employee.txt";
try
{
// Checking if the File is exists or not. If yes then a delete a File.
if (File.Exists(filePath))
{
// Delete a File
File.Delete(filePath);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Comments (0)