c# delete file in directory if exists

The Best way I can tell you is to check if the file is Read-only before you go on deleting it.

Lets see how this is done.

Say I am going to delete a file here C:\folder\a.txt

The code below will check for the file mode and then it will delete it if the file exists

[geshi lang=”csharp” nums=”1″ target=”_self” ]

try
{

if ((File.GetAttributes(“C:\folder\a.txt”) & FileAttributes.Hidden) == FileAttributes.readonly)
{
File.SetAttributes(“C:\folder\a.txt”, FileAttributes.Normal);

if (File.Exists(“C:\folder\a.txt”))
{
File.Delete(“C:\folder\a.txt”);
}
}

}catch(Exception e)
{
Console.WriteLine(e.Message); // check if something went wrong
}

FYI: To recursively delete a Directory you can do something like this

[geshi lang=”csharp” nums=”1″ target=”_self” ]

Directory.Delete(PATH_TO_DIR,true); // second parameter is setting recursive flag to true

Hope this helps

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.