我正在尝试使用 c# 删除远程服务器上的用户配置文件。我正在以自己的身份运行该程序。如果我以自己的身份浏览到 \\server\c$\Users\,我可以删除目录“用户”。它没有错误。如果我使用 C# 编写的程序和下面的代码来尝试删除同一个目录,我会得到这个异常。
拒绝访问路径“appsFolder.itemdata-ms”。
我的删除有问题吗?
Directory.Delete("\\\\server\\c$\\Users\\User\\",true);
我正在尝试使用 c# 删除远程服务器上的用户配置文件。我正在以自己的身份运行该程序。如果我以自己的身份浏览到 \\server\c$\Users\,我可以删除目录“用户”。它没有错误。如果我使用 C# 编写的程序和下面的代码来尝试删除同一个目录,我会得到这个异常。
拒绝访问路径“appsFolder.itemdata-ms”。
我的删除有问题吗?
Directory.Delete("\\\\server\\c$\\Users\\User\\",true);
删除用户配置文件文件夹而不清理注册表可能会导致一些不希望的副作用,例如临时配置文件创建等。我建议使用可以在 userenv.dll 中找到的 DeleteProfile 函数
我的代码如下:
internal class Program
{
[DllImport("userenv.dll", CharSet = CharSet.Unicode, ExactSpelling = false, SetLastError = true)]
public static extern bool DeleteProfile(string sidString, string profilePath, string omputerName);
private static void Main(string[] args)
{
try
{
var username = args[0];
var principalContext = new PrincipalContext(ContextType.Domain); // Domain => to support local user this should be changed probably, didn't test yet
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
if (userPrincipal != null)
{
Console.WriteLine("User found");
var userSid = userPrincipal.Sid;
Console.WriteLine("User {0} has SID: {1}", username, userSid);
Console.WriteLine("Will try to DeleteProfile next..");
DeleteProfile(userSid.ToString(), null, null);
Console.WriteLine("Done - bye!");
}
else
{
Console.WriteLine("ERROR! User: {0} not found!", username);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
}
考虑一下,此代码仅用于演示目的,应稳定用于生产..
干杯,
-克里斯
顺便说一句,这里有更多关于 MSDN https://msdn.microsoft.com/en-us/library/windows/desktop/bb762273(v=vs.85).aspx
嗨,我试图做同样的事情,发现 Directory.Delete() 如果文件是隐藏文件或系统文件,则无法删除文件。
使用 cmd 代替删除文件夹。
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);
}
}
调用这个
删除("c:\Users\"); // 在本地系统上执行此操作。
我还没有尝试过网络位置,但我认为这会起作用。
注意:要完全删除 userProfile,我们还需要删除注册表。