Run .bat file through C # code when user silently

I run one batch file every few seconds to execute the timesync command with the server using the following code:

Process process = new Process();

process.StartInfo.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System);

process.StartInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe");
process.StartInfo.Arguments = @"/C C:\TimeSync.bat";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UserName = "username";

SecureString pwd = new SecureString();

Char[] pwdCharacters = "password".ToCharArray();
foreach (char t in pwdCharacters)
{
    pwd.AppendChar(t);
}

process.StartInfo.Password = pwd;

process.Start();
string output = process.StandardOutput.ReadToEnd();

The problem is that it flashes the command windows on the screen, which I do not want. How can I prevent this?

One of the actions that I saw is that if I run the same code with UseShellExecute = trueand do not specify a username and password, then the command window does not blink.

So basically I want to run a .bat file using C # code as a user.

+3
source share
4 answers

Since you are passing in a username and password, the CreateNoWindow parameters are not respected. This is a function (i.e. Error) in windows. Here are the five-year connection details:

http://connect.microsoft.com/VisualStudio/feedback/details/98476/cmd-windows-shows-using-process-with-createnowindow-when-using-username-password-option

Process.Start() advapi32.dll CreateProcessWithLogonW CreateProcessWithLogonW . ,

" ": http://blogs.msdn.com/b/jmstall/archive/2006/09/28/createnowindow.aspx msdn .

stackoverflow: cmd ?

, , , , , . , , , , . , "" .

, lb

+1

:

process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;

 process.StartInfo.WindowStyle =
 ProcessWindowStyle.Hidden;

.

, !

+1

:

process.StartInfo.CreateNoWindow=true;

?

0

. , IDisposable , , .

0

Source: https://habr.com/ru/post/1784591/


All Articles