I am trying to use c# to delete a user profile on a remote server. I am running the program as myself. If I browse to \\server\c$\Users\ as myself I can delete the directory "User". It gives no error. If I use my program written in C# with the code below to attempt to delete the same directory I get back this exception.
Access to the path 'appsFolder.itemdata-ms' is denied.
Am I doing something wrong with my delete?
Directory.Delete("\\\\server\\c$\\Users\\User\\",true);
Hi I was trying to same thing and found Directory.Delete() cannot delete files if file is Hidden or a system file.
Using cmd instead to delete folder.
public static FileAttributes RemoveAttribute (FileAttributes att, FileAttributes attToRemove)
{
return att & ~attToRemove;
}
public void DeleteProfileFolder(string file)
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProvessWindowsStyle.Hiddenl
startInfo.FileName = "cmd";
startInfo.Arguments = "/C rd /S /Q \"" + file + "\"";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
}
public void Deletes(DirectoryInfo baseDir)
{
if(! baseDir.Exists)
return;
var Dirs = Directory.EnumerateDirectories(baseDir.ToString(),"*.*",SearchOption.TopDirectoryOnly);
var files = Directory.EnumerateFiles(baseDir.ToString(),"*.*",SearchOption.TopDirectoryOnly);
foreach(var dir in Dirs)
{
DeleteProfileFolder(dir);
}
foreach(var file in files)
{
FileAttributes att = File.GetAttributes(f);
if((att & FileAttributes.Hidden) == FileAttribute.Hidden)
{
att = RemoveAttribute(att, FileAttributes.Hidden);
File.SetAttributes(file , att);
File.SetAttributes(File, FileAttributes.Normal)
}
File.Delete(file);
}
}
To call This
Deletes("c:\Users\"); // did this on local system.
I havn't tried on network location but I thing this will work.
Note: To completely delete userProfile we also need to delete registry.