1. I have an application that needs to rename folders on a shared network drive.
2. These folders have subfolders and there may be files in the subfolders.
3. One or more of these files may be open in an application on the user's computer or another computer on the network.
When condition #3 is true, the folder rename fails. The user gets an error message, but they are then faced with the problem of what to close on their own machine and, worse, they may have to wander round the office trying to find out who has a file open.
It would be nice to present them with a list of the files that are open.
Below I show the code I have at the moment. It seems to work for files open in some applications but not others. For example, if a file is opened in Notepad or Notepad++, my code does not detect a problem, but Windows clearly is able to detect that Notepad has the file open because it refuses to rename the parent folder.
Is there any way to do this?
What I have tried:
private void TestFunction( string folderPath )
{
List<string> fileList = Directory.GetFiles( folderPath, "*", SearchOption.AllDirectories ).ToList();
List<string> filteredFileList = fileList.Where( f => IsFileLocked( f ) ).ToList();
}
private bool IsFileLocked( string filePath )
{
try
{
FileInfo fileInfo = new FileInfo( filePath );
using( FileStream stream = fileInfo.Open( FileMode.Open, FileAccess.ReadWrite, FileShare.None ) )
{
stream.Close();
}
}
catch( IOException )
{
return true;
}
return false;
}