Reputation: 91
I have created a shell script in C# that deletes Windows home folders on the server. The home folders are given by a text-file. The script loops thru the folders and deletes them. I have two log files a "success"-log and a "error"-log.
The deleting part looks like:
if (Directory.Exists(serverShare + "\\" + user))
{
try
{
Directory.Delete(serverShare + "\\" + user, true);
successLog.WriteLine(serverShare + "\\" + user + " --- deleted");
}
catch (Exception ex)
{
errorLog.WriteLine(serverShare + "\\" + user + " --- Error: {0}", ex.ToString());
}
}
else
{
errorLog.WriteLine(serverShare + "\\" + user + " -- Errror: Directory not exists!");
}
Now I run into an exception:
"System.IO.IOException: The process cannot access the file because it is being used by another process. directory.delete pictures documents".
The folder was not in use (the users who access it, works no longer in the company), so no another process can access it.
The exception occurs with folders my documents\my music
, my documents\my pictures
. So it could be do something with special Windows folders?
The other folders are deleted. So the script "works". Also no problems in local environment.
Upvotes: 1
Views: 3482
Reputation: 91
I have solved the problem. Some (system) folders have Archive or ReadOnly flags. It seems the Directory.Delete (with recursive subfolder deletion) can't delete these folders. So you have to remove these attributes first. Removing mehtod:
public static void ClearAttributes(string currentDir)
{
if (Directory.Exists(currentDir))
{
File.SetAttributes(currentDir, FileAttributes.Normal);
string[] subDirs = Directory.GetDirectories(currentDir);
foreach (string dir in subDirs)
{
ClearAttributes(dir);
}
string[] files = files = Directory.GetFiles(currentDir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
}
}
}
Then, before Directory.Delete run this method.
ClearAttributes(serverShare + "\\" + user);
Directory.Delete(serverShare + "\\" + user, true);
So it works fine and all folders are deleted.
Upvotes: 2
Reputation: 5157
Can you manually delete the folder ?
You can use this Process explorer
to get the locking file name.
https://technet.microsoft.com/en-sg/sysinternals/bb896653.aspx
Or you can put
GC.Collect();
Directory.Delete(serverShare + "\\" + user, true);
Upvotes: 1