You want to delete a file on the filesystem, detecting when documents are locked or unavailable. File.Delete throws an exception if this occurs.
First, File.Delete will permanently delete a file, bypassing the recycle bin. You must be also very careful with exceptions. File.Delete does not throw an exception when a file doesn't exist.
What that means is when exceptions are thrown, the file is locked. This is the metadata description for File.Delete:
// Summary: // Deletes the specified file. An exception is not thrown if the specified file // does not exist.
Catch IOException. The type we want to detect is the System.IO.IOException. The metadata says that this indicates that "The specified file is in use." Wrap the Delete call in another method that handles some of the errors.
using System.IO;
class Program
{
static void Main()
{
// 1.
// Call Delete wrapper method.
TryToDelete("Word.doc");
}
/// <summary>
/// Wrap the Delete method with an exception handler.
/// </summary>
static bool TryToDelete(string f)
{
try
{
// A.
// Try to delete the file.
File.Delete(f);
return true;
}
catch (IOException)
{
// B.
// We couldn't delete the file.
return false;
}
}
}Use a wrapper method with the File.Delete. You may have to prepare for other exceptions thrown by File.Delete. The code I present here purposely limits itself to IOException.
using System.IO;
using System.Diagnostics;
class Program
{
static void Main()
{
// See if the file is available.
if (TryToDelete("Word.doc") == false)
{
// a.
// File is not available.
// Tell user to close Word or Excel.
Debug.WriteLine("File is unavailable");
}
else
{
// b.
// File has been successfully deleted,
// or never existed.
Debug.WriteLine("File has been deleted.");
}
}
/// <summary>
/// Wrap the Delete method with an exception handler.
/// </summary>
static bool TryToDelete(string f)
{
try
{
File.Delete(f);
return true;
}
catch (IOException)
{
return false;
}
}
}Never make any assumptions about the filesystem: always check for errors and unexpected conditions. One other technique used by Paint.NET ensures that a path exists on the file system.