TechieClues TechieClues
Updated date Aug 19, 2022
This blog shows how to create and delete a file using StreamWriter & StreamReader in 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

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

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