Sabari M Sabari M
Updated date Jan 24, 2021
This blog shows how to create and delete a file using C#.

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 StreamWriterStreamReader.

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);
            }
        }
    }  
}

 

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

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