2

Use C# to copy WINDOWS log files to other disks. The main problem is that the CMD command with administrator privileges will not be called, and some of the things mentioned on the Internet will not work. private Process proc = null;

public Command()
{
proc = new Process();
}

public void RunCmd(string cmd)
{
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "C:\Windows\System32\cmd.exe";
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.Verb = "RunAs";
proc.Start();
proc.StandardInput.WriteLine(cmd);
proc.Close();
}
public void ChangeFile(string path1,string path2)
{
Command cmd = new Command();
cmd.RunCmd("attrib -s" + " " + path1);
Directory.CreateDirectory(path2);
cmd.RunCmd("Xcopy" + " " + path1 + " " + path2);
}

Hope someone can tell me how to fix it.

fly cat
  • 23
  • 5
  • 2
    You cannot redirect the input streams of a process started with elevation to its non-elevated parent; this is by design, to prevent exactly the kind of thing you're doing here (which would be a security hole). What you can do is write the commands you want to execute in advance to a `.cmd` file and then invoke the shell on that. If you need to capture output, redirect it to a file as part of the commands. Better yet, consider just writing some C# code to do what you're doing and run that process elevated (or use an installer framework), since troubleshooting shell commands is no fun. – Jeroen Mostert Feb 07 '23 at 13:32
  • 1
    Of course, if it turns out you actually don't *need* admin privileges (your question isn't clear on this), the solution is to not use `UseShellExecute` and `Verb = "RunAs"`, but I *assume* these were added deliberately. – Jeroen Mostert Feb 07 '23 at 13:39
  • 2
    `xcopy /h` would copy system files without having to remove their system attribute in the first place, which is probably kinder to anything expecting those files to retain their attributes. – Damien_The_Unbeliever Feb 07 '23 at 13:47

1 Answers1

1

You can restart a process as an administrator like this:

    ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\cmd.exe");
    info.UseShellExecute = true;
    info.Verb = "runas";
    Process.Start(info);

For details, please refer to Run process as administrator from a non-admin application

wenbingeng-MSFT
  • 1,546
  • 1
  • 1
  • 8