c# - 如何使用 takeown 或 icacls 在 c# 中获取文件的所有权?
问题描述
我知道还有其他关于此事的帖子,但没有人向我提供可行的解决方案。我正在尝试获取 C:\Windows\Media 下文件的所有权,以便我可以将它们替换为我自己的。目前我一直在尝试通过在 CMD 中运行 takeown 或 icacls 来做到这一点,但似乎都不起作用。takeown 方法实际上从 CMD 返回成功,但是在尝试删除文件时我仍然拒绝访问。使用 icacls 方法,我得到“句柄无效”并且仍然被拒绝访问。该程序以管理员身份运行,仅供参考。而且在 icacls 方法中,将 Environment.Username 更改为“Administrators”也不会改变任何内容。任何帮助表示赞赏!这是 takeown 方法的代码:
string[] soundFiles;
soundFiles = Directory.GetFiles(@"C:/Windows/Media", "*.wav");
//string cmdargs = @"/c takeown /F C:\Windows\Media";
string shortcmdargs = @"/c takeown /F ";
//Process.Start("CMD.exe", cmdargs);
string output = "null";
foreach(string file in soundFiles)
{
try
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = shortcmdargs + @"C:\Windows\Media\" + Path.GetFileName(file);
p.Start();
output = p.StandardOutput.ReadToEnd();
System.IO.File.Delete(file);
System.IO.File.Copy("neco.wav", file);
}
catch(Exception exce)
{
MessageBox.Show("Output: " + output + "\neException: " + exce);
}
}
这是 icacls 方法的代码:
string[] soundFiles;
soundFiles = Directory.GetFiles(@"C:/Windows/Media", "*.wav");
string cmdargs = @"/c takeown /F C:\Windows\Media";
string shortcmdargs = @"/c takeown /F ";
Process.Start("CMD.exe", cmdargs);
string output = "null";
foreach(string file in soundFiles)
{
try
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = @"/c icacls " + @"C:\Windows\Media\" + Path.GetFileName(file) + " /grant " + Environment.UserName + ":(OI)(CI)F /T";
p.Start();
output = p.StandardOutput.ReadToEnd();
System.IO.File.Delete(file);
System.IO.File.Copy("neco.wav", file);
}
catch(Exception exce)
{
MessageBox.Show("Output: " + output + "\neException: " + exce);
}
}
解决方案
推荐阅读
- javascript - 在 Google 表单中为批准工作流程创建脚本
- javascript - 如何从 Jenkins 将远程机器上的文件上传到 Amazon s3
- flutter - Flutter: Searching Through List
- swift - 如果用户已经评分,则禁用从用户那里获取应用评论
- ruby-on-rails - 动作电缆检测多个连接/标签
- r - 需要根据另一列将列中的na替换为averageif
- c# - 无法使用 SFTP/SSH.NET 从远程目录中删除文件?
- r - R simmer 简单的矿山模拟
- ruby-on-rails - rails active record 从继承的表中查找记录
- lua - (Corona SDK)场景转换不播放