Powered by Blogger.

Sunday, February 23, 2014

Delete file in C#.Net



In this article we will discuss about how can we delete a file from a directory in C#.Net. Also check out:

- Read and write from Text file in Asp.Net

- Ten Tips for Optimizing SQL Server Performance

- Convert first letter to uppercase in C#.Net

Microsoft provides System.IO namespace to work with files and directory. Here we will use the FileInfo class to delete the file.

FileInfo class has a delete method that will Delete() the file from the specified location. But before calling the Delete() method it is better to check wether the file is exists or not by using the Exists property.

Below is the full C#.Net code to delete file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class DeleteFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DeleteFileFromDrive();
    }
    void DeleteFileFromDrive()
    {
        try
        {
            string path = "C:\\DeleteFile.txt";
            FileInfo file = new FileInfo(path);
            if (file.Exists)
            {
                file.Delete();
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

The above code will delete the file from the C drive.





0 comments

Post a Comment