<p>I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:</p>

<pre><code>SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
    password.AppendChar(c);

ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "builder";
psi.Password = password;
Process.Start(psi);
</code></pre>

<p>If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).</p>

<p>The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?</p>

<p><strong>EDIT:</strong> See my answer below for the contents of the batch file.</p>

<ul>
<li>The output.txt never gets created.</li>
</ul>

<p>I added these lines:  </p>

<pre><code>psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
String outp = p.StandardOutput.ReadLine();
</code></pre>

<p>and stepped through them in debug mode. The code hangs on the <code>ReadLine()</code>. I'm stumped!</p>

[{'answer_id': 34187, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 0, 'selected': False, 'text': '<p>My guess would be that the build.cmd is waiting for some sort of user-interaction/reply. If you log the output of the command with the "<strong>> logfile.txt</strong>" operator at the end, it might help you find the problem.</p>\n'}, {'answer_id': 34191, 'author': 'Martin Marconcini', 'author_id': 2684, 'author_profile': 'https://Stackoverflow.com/users/2684', 'pm_score': 2, 'selected': False, 'text': '<p>Without seeing the build.cmd it\'s hard to tell what is going on, however, you should build the path using Path.Combine(arg1, arg2); It\'s the correct way to build a path. </p>\n\n<pre><code>Path.Combine( Environment.SystemDirectory, "cmd.exe" );\n</code></pre>\n\n<p>I don\'t remember now but don\'t you have to set UseShellExecute = true ?</p>\n'}, {'answer_id': 34193, 'author': 'Biri', 'author_id': 968, 'author_profile': 'https://Stackoverflow.com/users/968', 'pm_score': 1, 'selected': False, 'text': '<p>Another possibility to "debug" it is to use standardoutput and then read from it:</p>\n\n<pre><code>psi.RedirectStandardOutput = True;\nProcess proc = Process.Start(psi);\nString whatever = proc.StandardOutput.ReadLine();\n</code></pre>\n'}, {'answer_id': 34197, 'author': 'Josh Hinman', 'author_id': 2527, 'author_profile': 'https://Stackoverflow.com/users/2527', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s the contents of build.cmd:</p>\n\n<pre><code>@echo off\nset path=C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727;%path%\n\nmsbuild myproject.csproj /t:Build &gt; output.txt\nIF NOT ERRORLEVEL 1 goto :end\n\n:error\nbmail -s k2smtpout.secureserver.net -f build@example.com -t josh@example.com -a "Build failed." -m output.txt -h\n\n:end\ndel output.txt\n</code></pre>\n\n<p>As you can see, I\'m careful not to output anything. It all goes to a file that gets emailed to me if the build happens to fail. I\'ve actually been running this file as a scheduled task nightly for quite a while now. I\'m trying to build a web app that allows me to run it on demand.</p>\n\n<p>Thanks for everyone\'s help so far! The Path.Combine tip was particularly useful.</p>\n'}, {'answer_id': 34205, 'author': 'Martin Marconcini', 'author_id': 2684, 'author_profile': 'https://Stackoverflow.com/users/2684', 'pm_score': 1, 'selected': False, 'text': '<p>In order to "see" what\'s going on, I\'d suggest you transform the process into something more interactive (turn off Echo off) and put some "prints" to see if anything is actually happening. What is in the output.txt file after you run this?</p>\n\n<p>Does the bmail actually executes?</p>\n\n<p>Put some prints after/before to see what\'s going on. </p>\n\n<p>Also add "@" to the arguments, just in case: </p>\n\n<pre><code>psi.Arguments = @"/q /c build.cmd";\n</code></pre>\n\n<p>It has to be something very simple :)</p>\n'}, {'answer_id': 34801, 'author': 'sieben', 'author_id': 1147, 'author_profile': 'https://Stackoverflow.com/users/1147', 'pm_score': 0, 'selected': False, 'text': '<p>I think cmd.exe hangs if the parameters are incorrect.</p>\n\n<p>If the batch executes correctly then I would just shell execute it like this instead.</p>\n\n<pre><code>ProcessStartInfo psi = new ProcessStartInfo();\nProcess p = new Process();\npsi.WindowStyle = ProcessWindowStyle.Hidden;\npsi.WorkingDirectory = @"c:\\build";\npsi.FileName = @"C:\\build\\build.cmd";\npsi.UseShellExecute = true;\npsi.UserName = "builder";\npsi.Password = password;\np.StartInfo = psi;\np.Start();\n</code></pre>\n\n<p>Also it could be that cmd.exe just can\'t find build.cmd so why not give the full path to the file?</p>\n'}, {'answer_id': 38072, 'author': 'Martin Marconcini', 'author_id': 2684, 'author_profile': 'https://Stackoverflow.com/users/2684', 'pm_score': 0, 'selected': False, 'text': "<p>What are the endlines of you batch? If the code hangs on ReadLine, then the problem might be that it's unable to read the batch file…</p>\n"}, {'answer_id': 38164, 'author': 'sieben', 'author_id': 1147, 'author_profile': 'https://Stackoverflow.com/users/1147', 'pm_score': 2, 'selected': False, 'text': '<p>Why not just do all the work in C# instead of using batch files?</p>\n\n<p>I was bored so i wrote this real quick, it\'s just an outline of how I would do it since I don\'t know what the command line switches do or the file paths.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Text;\nusing System.Security;\nusing System.Diagnostics;\n\nnamespace asdf\n{\n    class StackoverflowQuestion\n    {\n        private const string MSBUILD = @"path\\to\\msbuild.exe";\n        private const string BMAIL = @"path\\to\\bmail.exe";\n        private const string WORKING_DIR = @"path\\to\\working_directory";\n\n        private string stdout;\n        private Process p;\n\n        public void DoWork()\n        {\n            // build project\n            StartProcess(MSBUILD, "myproject.csproj /t:Build", true);\n        }\n\n        public void StartProcess(string file, string args, bool redirectStdout)\n        {\n            SecureString password = new SecureString();\n            foreach (char c in "mypassword".ToCharArray())\n                password.AppendChar(c);\n\n            ProcessStartInfo psi = new ProcessStartInfo();\n            p = new Process();\n            psi.WindowStyle = ProcessWindowStyle.Hidden;\n            psi.WorkingDirectory = WORKING_DIR;\n            psi.FileName = file;\n            psi.UseShellExecute = false;\n            psi.RedirectStandardOutput = redirectStdout;\n            psi.UserName = "builder";\n            psi.Password = password;\n            p.StartInfo = psi;\n            p.EnableRaisingEvents = true;\n            p.Exited += new EventHandler(p_Exited);\n            p.Start();\n\n            if (redirectStdout)\n            {\n                stdout = p.StandardOutput.ReadToEnd();\n            }\n        }\n\n        void p_Exited(object sender, EventArgs e)\n        {\n            if (p.ExitCode != 0)\n            {\n                // failed\n                StringBuilder args = new StringBuilder();\n                args.Append("-s k2smtpout.secureserver.net ");\n                args.Append("-f build@example.com ");\n                args.Append("-t josh@example.com ");\n                args.Append("-a \\"Build failed.\\" ");\n                args.AppendFormat("-m {0} -h", stdout);\n\n                // send email\n                StartProcess(BMAIL, args.ToString(), false);\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 38331, 'author': 'Josh Hinman', 'author_id': 2527, 'author_profile': 'https://Stackoverflow.com/users/2527', 'pm_score': 4, 'selected': True, 'text': '<p>I believe I\'ve found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:</p>\n\n<p><a href="http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx" rel="noreferrer">http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx</a></p>\n\n<p>That won\'t work for me, because my batch file uses IF and GOTO, but it would definitely work for simple batch files.</p>\n'}]
['https://Stackoverflow.com/questions/34183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2527/']