Tuesday, April 29, 2008

How to delete a file in C# ?

Many times a C# programmer has to delete files present on the hard drive. Deleting a file in C# is very simple, since most of the functionality is already provided by .NET framework. Here is a code that first checks if a file exists at a given path and if so, then deletes the file.


/// <summary>

/// Deletes the specified file

/// </summary>

/// <param name="fileToDelete">File (path) to be deleted.</param>wi

/// <returns>bool value indicating whether the file was deleted.</returns>

public bool DeleteFile(string fileToDelete)

{

try

{

if (File.Exists(fileToDelete))

{

File.Delete(fileToDelete);

return true;

}

else

return true;

}

catch (Exception ex)

{

// Log the exception

return false;

}



}

11 comments:

Anonymous said...

You need to add
using System.IO aswell. Maby you should mention it

Anonymous said...

if return true;
else it should be return false...

Subrahmanyam Kota said...

How to delete all Temnp files dynamically ? While they are in use ??

While deleting by using - GetTempPath()

Getting exception ? Help me.

- KVS (skotaji@gmail.com)

Anonymous said...

"Anonymous said...
if return true;
else it should be return false...
"

No, it should return true. True means that the file has been deleted, either by this code or outside it. False means that the delete's gone wrong and the file is still there.

Anonymous said...

So write :

public bool DeleteFile(string fileToDelete){try{if (File.Exists(fileToDelete)) File.Delete(fileToDelete);
return true;
;}catch (Exception ex){// Log the exception
return false;}}

Anonymous said...

Thanks buddy...

Anonymous said...

great man

Ward said...

Thanks!

Anonymous said...

Hi, i couldnt able to delete file using above mention way.............

is there any other way to perform it...

Anonymous said...

remove("filename");

Anonymous said...

check it
http://www.csharp-examples.net/filestream-read-file/

Post a Comment