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:
You need to add
using System.IO aswell. Maby you should mention it
if return true;
else it should be return false...
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...
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.
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;}}
Thanks buddy...
great man
Thanks!
Hi, i couldnt able to delete file using above mention way.............
is there any other way to perform it...
remove("filename");
check it
http://www.csharp-examples.net/filestream-read-file/
Post a Comment