首页 > 解决方案 > 如何使用 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);
            }
            
        }

这是我得到的: 错误信息

标签: c#.netwindowscmd

解决方案


推荐阅读