CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Brendan Tompkins [MVP]

Blog First. Ask Questions Later.

Run a .BAT file from ASP.NET

Okay, running .BAT files from ASP.NET using  the System.Diagnostics.Process object and static methods this should be easy, right?  Well, this might work for you, but it certainly won't work on my machines. And after doing lots of reasearh on the issue, it seems that other people are also having problems with this too.  

I wrestled with permissions and all sorts of other stuff, trying to get a simple batch file to run, with no luck.  I tried lauching the bat file directly, launching cmd.exe and calling the bat file using stin. No dice.  It seems that something on my machine was keeping an unattended process from running bat files.  This makes sense, but I was never able to pinpoint what was preventing this, so I came up with a workaround.

I realized that since I could sucessfully run cmd.exe, and send commands to it via stin, I could just open the batch file, and send each line to cmd.exe, which is essentially the same as running a batch file itself.  This technique works great, and I thought I'd pass along the code here.

// Get the full file path
string strFilePath = “c:\\temp\\test.bat”;

// Create the ProcessInfo object
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute =
false;
psi.RedirectStandardOutput =
true;
psi.RedirectStandardInput =
true;
psi.RedirectStandardError =
true;
psi.WorkingDirectory = “c:\\temp\\“;

// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);

// Open the batch file for reading
System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);

// Attach the output for reading
System.IO.StreamReader sOut = proc.StandardOutput;

// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;

// Write each line of the batch file to standard input
while(strm.Peek() != -1)
{
  sIn.WriteLine(strm.ReadLine());
}

strm.Close();

// Exit CMD.EXE
string stEchoFmt = "# {0} run successfully. Exiting";

sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
sIn.WriteLine("EXIT");

// Close the process
proc.Close();

// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();

// Close the io Streams;
sIn.Close();
sOut.Close();

// Write out the results.
string fmtStdOut = "<font face=courier size=0>{0}</font>";
this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "<br>")));

That's it!   Works like a charm! 

-Brendan



Comments

Brendan Tompkins said:

Lorenzo,

I don't think so, since we're running server 2003. It could be a security setting, I agree, but I checked all the standard stuff, like permissions and that didn't seem to be the problem.
# May 14, 2004 1:56 AM

Chris Kinsman said:

Did you try cmd /c
# May 14, 2004 5:01 AM

Brendan Tompkins said:

Chris. I tried this, to no effect. It was like something low level was stopping the cmd.exe process from executing a bat file. Strange.
# May 14, 2004 5:05 AM

Eric Engler said:

Can you run a VBScript from ASP.NET? You might try running a VBScript that, in turn, calls a batch. Something like this:

Save this as a name.vbs file and call it from your code-behine:
---------------------------
Const NOWAITFORFINISH = 0
Const WAITFORFINISH = 1
Const HIDEWINDOW = 0
Const SHOWWINDOW = 1

Dim oShell, sCommand
sCommand = "c:\path\batch.bat"
Set oShell = Wscript.CreateObject("Wscript.Shell")
oShell.Run Quote(sCommand), HIDEWINDOW, NOWAITFORFINISH

WScript.Quit(0)

Function Quote(sText)
Quote = Chr(34) & sText & Chr(34)
End Function
# May 17, 2004 6:53 AM

Matt said:

Brendan your code works fine on my Windows 2000 server but on my Windows 2003 server I get the following error message...

Access is denied

at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) at System.Diagnostics.Process.Start() at System.Diagnostics.Process.Start(ProcessStartInfo startInfo) at cis2004.resumertf.Page_Load(Object sender, EventArgs e)

Any ideas?

Thank in advance - Matt
# May 24, 2004 10:53 AM

Brendan Tompkins said:

Hi Matt,
Get yourself a copy of FileMon from Sysinternals.

http://www.sysinternals.com/

Run this on the server and look for ACCESS DENIED messages, or some other error. This can get a bit tricky to get working...

I think that the local machine's NETWORK SERVICE account has to have rights to open dirs, etc..
# May 25, 2004 7:41 AM

Dan said:

This code works great but I can't get anything to run in the batch file other than a simple net send. What account does the batch file run as? Seem like it doesn't have permissions to delete or copy files.
# June 15, 2004 8:51 AM

Brendan Tompkins said:

Hi Dan.. See the above comments I left for Matt.
# June 15, 2004 8:53 AM

Dan said:

Thanks Brendan,

I already did install FileMon and all it seems to tell me is if the batch file failed or not. Is there some option to see who the batch file ran as? Can you somehow change the account the batch file runs as?

I think I need mine to run as a domain account and not the local system because the files I am working with are not on the webserver.

BTY, great code!!! I don't even know C# and I was able to get it working (Just cut and paste)

Thanks,
Dan
# June 16, 2004 12:13 AM

Brendan Tompkins said:

Dan,

Thanks! Try TokenMon from Sysinternals. Under 2003, these batch files run as NETWORK SERVICE, AFAIK....
# June 16, 2004 2:05 AM

Dan Marth said:

Brendan,
FYI, I am running this on windows 2000 but I will take a look at TokenMon.

Thanks,
Dan
# June 16, 2004 2:44 AM

Dan Marth said:

I don't think TokenMon is going to tell me anyting since it reboots the server everytime I have TokenMon running and try to hit the webpage that calls the batch file. Reboots everytime! Any other ideas?

Thanks,
Dan
# June 16, 2004 1:09 PM

Brendan Tompkins said:

Ha. I've had that happen too. Well, are you sure filemon doesn't tell you the process user? Have you tried granting permissions to the NETWORK SERVICE account on the local box?

# June 16, 2004 1:53 PM

Dan Marth said:

This is what I get from filemom....Looks like it might be running as system but if I give system full access......still no dice!!!

343 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS SUCCESS Options: Open Access: All
344 7:21:19 AM System:8 FASTIO_QUERY_BASIC_INFO C:\RCS SUCCESS Attributes: D
345 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS SUCCESS
346 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS SUCCESS
347 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS SUCCESS Options: Open Directory Access: Traverse
348 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS BUFFER OVERFLOW FileNameInformation
349 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS SUCCESS FileNameInformation
350 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS\V14\DATA66\DATA SUCCESS Options: Open Access: All
351 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS\V14\DATA66\DATA SUCCESS FileBasicInformation
352 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS\V14\DATA66\DATA SUCCESS
353 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS\V14\DATA66\DATA SUCCESS
354 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS SUCCESS
355 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS SUCCESS
356 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS SUCCESS Options: Open Access: All
357 7:21:19 AM System:8 FASTIO_QUERY_BASIC_INFO C:\RCS SUCCESS Attributes: D
358 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS SUCCESS
359 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS SUCCESS
360 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS SUCCESS Options: Open Directory Access: Traverse
361 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS BUFFER OVERFLOW FileNameInformation
362 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS SUCCESS FileNameInformation
363 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS Options: Open Access: All
364 7:21:19 AM System:8 FASTIO_QUERY_NETWORK_OPEN_INFO C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS Attributes: D
365 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS FileEaInformation
366 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS FileStreamInformation
367 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS FileObjectIdInformation
368 7:21:19 AM System:8 IRP_MJ_QUERY_SECURITY C:\RCS\V14\DATA66\DATA\HotHits.bat BUFFER OVERFLOW
369 7:21:19 AM System:8 IRP_MJ_QUERY_SECURITY C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS
370 7:21:19 AM System:8 FASTIO_READ C:\RCS\V14\DATA66\DATA\HotHits.bat FAILURE Offset: 0 Length: 4096
371 7:21:19 AM System:8 IRP_MJ_READ C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS Offset: 0 Length: 4096
372 7:21:19 AM System:8 IRP_MJ_CLOSE C:...\\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS
373 7:21:19 AM System:8 FASTIO_READ C:\RCS\V14\DATA66\DATA\HotHits.bat END OF FILE Offset: 79 Length: 4017
374 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS
375 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS SUCCESS
376 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS SUCCESS
377 7:21:20 AM System:8 IRP_MJ_WRITE* C: SUCCESS Offset: 11112448 Length: 4096
378 7:21:20 AM System:8 IRP_MJ_WRITE* C: SUCCESS Offset: 12288 Length: 4096
379 7:21:20 AM System:8 IRP_MJ_WRITE* C: SUCCESS Offset: 0 Length: 4096

As far as permissions, the everyone domain group has full permissions so that should cover everything but I did try adding the NETWORK account and it didn't work. I couldn't find a NETWORK SERVICE account? Only network.
# June 17, 2004 12:26 AM

Dan Marth said:

It looks like the only way it will work is if the batch file is located and runs all commands on the webserver.....that seems to work fine.


Trying to copy, or in my case run a scanlog program on another server, just isn't going to work. Am I correct?

Thanks for all the help,
Dan
# June 17, 2004 1:34 AM

Dan Marth said:

Brendan,

Is there anyway I could get a VB version of this code? It is working great but I don't know CSharp and I am having an hell of a time trying to add a drop down box that a user can select a program, hit submit, and the path to the batch file will use the selected program (which is a different path).

So I am going to have 60 different paths to the batch file (which will scan the log files in those directories).

“c:\\Hot Hits\\test.bat”;
“c:\\Classical\\test.bat”;
“c:\\Jazz\\test.bat”;
and so on....I just can get it to work in CSharp (I can't even get a button to work).

Thanks,
Dan
# July 5, 2004 1:17 AM

Dan Marth said:

Brenden,

Please disregard, I got it working in CSharp with the help of some nice guy on aspmessageboard. Working great!!!

Thanks,
Dan
# July 6, 2004 1:35 AM

Brendan Tompkins said:

Dan - Good. BTW, anyone know of any tools to port from C# to VB?
# July 6, 2004 2:42 AM

Dan said:

Brenden,

Is there anyway to get the batchfile to run from a certain directory? I am using some old scanlog program that doesn't always work if it isn't run from the same directory as the log files it is scanning. It seems like it keeps running the batch file from C:\WINNT even if I put a CD in the batch file....see below?


C:\WINNT>CD C:\RCSFiles\HHI

C:\WINNT>scanlog.exe /p /2 /U1 *.HHI

C:\WINNT># c:\RCSFiles\HHI\ScanLog.bat run successfully. Exiting
# July 20, 2004 9:31 AM

Dan Marth said:

Sorry about the mis-spelling of your name.
# July 20, 2004 11:53 AM

Brendan Tompkins said:

Dan,

You could try setting this line to your directory, but I'm not positive it works.. I seem to remember having trouble with this.

psi.WorkingDirectory = “c:\\temp\\“;
# July 21, 2004 2:11 AM

TrungGap said:

Hi all,

I was having problem executing a batch file on Windows 2003 Server also. The code seems to execute fine on Windows 2000 Server. After playing around with it, I discovered the cause what was causing the problem, but still haven't fully understand why. Anyway, hopefully this little tibbits would help somebody.

This piece of code works perfectly on Win2K Server:

Process myProcess = new Process();
myProcess.StartInfo.WorkingDirectory = Request.MapPath("resources/files");

myProcess.StartInfo.FileName = Request.MapPath("resources/files/build.bat");
myProcess.StartInfo.Arguments = Request["Language"];
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.Start();

myOutput = myProcess.StandardOutput.ReadToEnd();

myProcess.WaitForExit();

However that didn't work on Win2K3 Server. The problem was if any commands in the batch file result in an error, it would exit. Thus in the batch had some del's to make sure the directory is clean, if it didn't delete anything, then it would exit.

To get around this, I had to redirect the standard error:

myProcess.StartInfo.RedirectStandardError = true;

# July 22, 2004 11:04 AM

Brendan Tompkins said:

Nice! Thanks!
# July 22, 2004 12:44 PM

Mike said:

I am having the same problem! Has anyone found a solution to this? I cannot seem to run a BAT file from ASP.NET, however, running it directly on the server works fine. I am sure it is a permissions issue, but I am not sure how to work around it!

Thanks,
mike
# August 9, 2004 3:18 AM

Oliver said:

Having the same problem on Win2k3 server. All directories have full permissions for Everyone (development server :)). Still no success. The .bat file runs fine locally, but does nothing when called from an ASP.NET process.
Any help is greatly appreciated.
# September 10, 2004 7:46 AM

Yaheya Quazi said:

You need to give access to IUSR_machinename account Read and Execture permission to cmd.exe also you have to add the following to your web.config file

<identity impersonate="true" />

Thanks!
# September 17, 2004 8:01 AM

Serge said:

Brendan,
Thanks for beatifull solution of the problem.

There are no need to read any batch file if you want to run the static command.
Instead of :
while(strm.Peek() != -1)
{
sIn.WriteLine(strm.ReadLine());
}
you can write:

sIn.WriteLine(strCmd);
Where strCmd is any command valid in command prompt. For example:
string strCmd = @"findstr /i /m " + "stringToFind" + " " + strDirectory + "\\*.*";
Return a file list contained "stringToFind".
Serge
# September 30, 2004 9:53 AM

Michael said:

Brendan,

Thanks for this ... MS should be shot for making it so difficult to run a simple batch file !

-- Michael
# October 14, 2004 12:35 PM

Sunil said:

Try this!! Works fine on W2K

Process myCmd = null;
ProcessStartInfo qOptions = new ProcessStartInfo(@"cmd.exe",@"/k C:/trigger.bat");
qOptions.WindowStyle = ProcessWindowStyle.Hidden;
qOptions.RedirectStandardOutput = false; // set to "true" to enable logging
qOptions.UseShellExecute = true; // set to true to make silent/background

myCmd = Process.Start(qOptions);
myCmd.WaitForExit();
# October 15, 2004 9:41 AM

viki said:

Hi,
i was trying to run an application(for e.g., notepad) thru the batch file.But my application hangs, i could see the notepad process running in the task manager, but i could not see the command window or notepad.

If my batch file has del or copy command it works eventhough i could not see the command window.

i have set integrated windows authentication and identity impersonate=true.

could u please shed a light on this
# October 26, 2004 1:50 PM

Somayeh said:

hello
i have few questions about this code.
from where this batch file will be executed?i mean does it execute the batch file on the server or on the clients???
i guess it runs on the server..but if i want to have a batch file on the server and i want it to be execute everytime a user send a request to that page..what should i do??
i want the batch file to be executed on the client and do something on the client machin.
# October 30, 2004 12:05 AM

Ramesh said:

Thanx I will try and then send another reply
# November 1, 2004 10:15 PM

HELP said:

i run process.start("send.bat","net-software test" for net send message "test" for net-software computer . but this code runing in win 2000 server and cant run in win 2003 server
# November 10, 2004 12:25 AM

Dariwe said:

I am having issues on winxp sp2. Everything is golden on win2k3 and xpsp1, but on 2 sp2 machines the debugger goes through the function where it is processing the batch file as expected, but the batch file just is not run. Any ideas?
# November 12, 2004 6:26 PM

Kien said:

For win2k3 users (like me) suffering with permissions and security, try http://www.eggheadcafe.com/articles/20030703.asp. Just this morning this helped me solve my permissions issue problem with an intranet app.
# November 17, 2004 3:27 AM

Jan Landen said:

Thank you Brendan!

It was a bit difficult to handle process standard io redirection to me...

Your code was great help to me to learn the basics....

-Jan
# November 18, 2004 1:26 AM

MadRiverLizard said:

How would I modify this so that the process uses command line arguments (c:\bat.bat 2004 1)?
# December 13, 2004 11:56 PM

lastdragon said:

none of the above suggestions seem to work
# December 20, 2004 9:34 AM

Jason said:

Anyone know how i can make it into a dataset. ie. ability to make each line a record in a virtual datasource? for datagrid use, etc.

Jason
# December 26, 2004 3:57 PM

Alex said:

In my case (Win 2003) it was completely permissions problem. I added Everyone with read writ execute permissions and it worked. I am going to take out permissions for everyone and add needed once.
# December 27, 2004 10:34 AM

Utkal Sharma said:

Oh boy.... Getting this thing working was like climbing Mount Everest. The code to run through cmd.exe was good but only if the processing which is done in .BAT file is small. In my case it may take 1-2 hour and so the cmd.exe was locking after the Script-timeout for aspx page is reached. In that case we have to make UseShellExecute = true so that it runs in background. Sunil's code(Below) works fine in such case.

Process myCmd = null;
ProcessStartInfo qOptions = new ProcessStartInfo(@"cmd.exe",@"/k C:/trigger.bat");
qOptions.WindowStyle = ProcessWindowStyle.Hidden;
qOptions.RedirectStandardOutput = false; // set to "true" to enable logging
qOptions.UseShellExecute = true; // set to true to make silent/background

myCmd = Process.Start(qOptions);
# January 6, 2005 12:23 PM

Marck NOOB said:

Is that possible to someone please write a full aspx page, calling a bat file ??

Please help me, I am very boob! :D
# February 9, 2005 11:38 AM

Ivan Belov said:

Thanks for snippet, Brendan! Helped me to solve related problem. Great job! :))
# June 14, 2005 1:45 PM

Tim Riester said:

AAAAACCCCKKK!!! I implemented this code in VB.NET on my web app and it runs great on my local web server which is Windows XP. When I move it to the production server which is W2K3, the batch files don't run. I've tried giving the Network Service acct on the machine full control over the batch files and the c drive, but still getting the same results of the batch files not being able to run. Any help would be appreciated. Thanks.

-Tim
# July 20, 2005 8:51 AM

Abhi said:

Thanks so much Brendon, it works, and shld say 'finally it works'.
I have spent hours to get this right. Ur logic and technique are very correct. Great work.
But please do mention above ur codes that, the user account under which the ASPNET runs should have full permissions.
I created a new user login, with admin access, and added the identitity impersonate = true in webconfig file
eg : <identity impersonate = "true" userName="SingpostPrintUser" password="singpost"></identity>

It should work now...

regards
abhi
# October 3, 2005 6:36 AM

Sudeep Ghosh said:

Hi,
I am facing the same problem ... it says the following

10060 - Connection timeout
Internet Security and Acceleration Server

--------------------------------------------------------------------------------

Technical Information (for support personnel)

Background:
When the server, while acting as a gateway or proxy, contacted the upstream content server, it did not receive a timely response.



Do I have the work around for this.... I need the connection to stay longer for some back ground process to work.

Please let me know if you have found the solution to this problem.

Thanks in advance

Thanks and Regards
Sudeep
sudeep_aitian@yahoo.com
# February 9, 2006 3:41 AM

darktown said:

for those who want the vb -code so badly
it took me 2 mins to convert it..


Dim strFilePath As String = "c:\\temp\\test.bat"

Dim psi As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo("cmd.exe")
psi.UseShellExecute = False
psi.RedirectStandardOutput = True
psi.RedirectStandardInput = True
psi.RedirectStandardError = True
psi.WorkingDirectory = "c:\\temp\\"

Dim proc As System.Diagnostics.Process = System.Diagnostics.Process.Start(psi)
Dim strm As System.IO.StreamReader = System.IO.File.OpenText(strFilePath)
Dim sout As System.IO.StreamReader = proc.StandardOutput
Dim sin As System.IO.StreamWriter = proc.StandardInput

While strm.Peek() <> -1
sin.WriteLine(strm.ReadLine())
End While

strm.Close()

Dim stEchoFmt As String = "# {0} run successfully. Exiting"
sin.WriteLine(String.Format(stEchoFmt, strFilePath))
sin.WriteLine("EXIT")
proc.Close()

sin.Close()
sout.Close()
# February 17, 2006 10:14 AM

Tracy Spratt said:

Well, y'all are getting me closer than any other site I have found!

Since I have just a single command to run I am trying to use Serge's suggestion () of writing the command directly to the sIn but am having a bit of trouble.

A hardcoded line works fine, but whenever I try to concatenate a variable, the command string, the command fails.

this works:
sCommand = "psshutdown.exe \\172.31.255.57 -u Administrator"
this works:
sCommand ="psshutdown.exe \\" & "172.31.255.57" & " -u Administrator"
but this fails:
sCommand ="psshutdown.exe \\" & sIP & " -u Administrator"

The WriteLine() has an overload that is supposed to take string.

Any ideas what is happening?

Alternatively, how could I parameterize the bat/cmd file if I used the sIn approach? I tried passing in a SET IP= to the cmd process, but this did not seem to work. Is that a valid approach?

It is silly that something so basic should be so hard!

TIA
Tracy
# February 21, 2006 9:55 PM

Tracy Spratt said:

I spoke too soon. Nothing is working on my win 2003 box. I have opened up every security resrtiction I can think of. Rats!
Tracy
# February 21, 2006 10:57 PM

Anupam Srivastava said:

Hi Brendan,
Your code is really good. However I'm stuck up at a point. Could you please tell me how do I pass parameters to my batch file?? I have tried giving
psi.Arguments = "123" ( in VB)
The code works fine but my batch file does not show any effect of the passed parameter. My batch file is :
copy h1.txt+h2.txt result%1.txt /B

I want the output as result123.txt but it comes as result%1.txt.

What's wrong with my code? Is it with batch file code or VB code??

Please help.
Anupam
# February 27, 2006 6:46 AM

James said:

Wow, just hit this after some searching and hair removing(insert frustration image here). This was by far the most helpful.

Thanks!
# March 2, 2006 7:36 PM

vikas kumar said:

this is my question

i m making a project in which i have to run cmd.exe from client machine

i am making project in asp.net using vb.net

if any one help me out please mail me at

viks_mumu@yahoo.co.in
# April 25, 2006 6:00 AM

Deepak said:

ok..tried all of the above. this does not work. W2K3 permissions is killing me. Always getting Access Denied error. I even impersonated as xxx who is admin on the server and has full permissions on network.
Any suggestions?
# June 13, 2006 11:40 AM

percyboy said:

The codes really work!
but it doesn't support the "goto label" grammer.
# June 14, 2006 2:32 AM

Kumar said:

Hi    Yaheya Quazi ,
Thanks ya,we were facing a problem while running .Bat file from local machine throgh ASP.NET application on W2k3 server.But your inputs are great in this issue and we are now able to run the .Bat file on the W2k3 server.


Thanks
Kumar
# June 29, 2006 12:53 AM

P. Ravichandran said:

On the above given code is not working properly in the ASPX page.  But is working on the Windows Application.  In ASPX page we need to close the input file before close the process.  Here i give the solution.

ProcessStartInfo ProObj = new ProcessStartInfo("cmd.exe");
ProObj.UseShellExecute = false;
ProObj.RedirectStandardOutput = true;
ProObj.RedirectStandardInput = true;
ProObj.RedirectStandardError = true;

Process proc = System.Diagnostics.Process.Start(ProObj);
StreamReader Sr = File.OpenText(@"E:\test.bat");
StreamReader sOut = proc.StandardOutput;
StreamWriter sIn = proc.StandardInput;

while(Sr.Peek() != -1)
{
         sIn.WriteLine(Sr.ReadLine());
}
Sr.Close(); //We must close it Here not after the process closing
sIn.WriteLine("EXIT");
sIn.Close();
proc.Close();
string result = sOut.ReadToEnd();
sOut.Close();
Response.Write(result);
# July 7, 2006 5:43 AM

Ipun said:

no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
# July 7, 2006 1:14 PM

Morgan said:

In windows 2003 you need to give Execute permissions to cmd.exe for your application pool user.
I also added a
psi.WindowStyle = ProcessWindowStyle.Hidden
but i dont know if its required.
# July 13, 2006 7:29 AM

Sashanan said:

This code solved my problem, at least. Thanks for sharing.
# July 24, 2006 3:58 AM

JOse said:

dsa
# July 26, 2006 11:43 AM

Sara said:

Hi there, I am constantly running in problem for calling a batchfile through asp.net. I read your whole article which apparently helped a lot of ppl but unfortunately not me.
I wrote this 3 lines code in VB.Net and it works perfectly fine.
       Dim proc As New System.Diagnostics.Process
       proc.StartInfo.FileName = "c:\\MyImport\\Convergys.bat"
       proc.Start()
I tried by all means to run through asp.net(working on server)...No luck at all.I load my batch file on server as well but didnt work.I have all permissions as per my Network guy.
It just doesnt call batch file thru asp.net.
I dont know how to give all permissions to ASPNET thing. May be that the problem i am having....Dont know.
My boss is really mad at me and I want some body's help really soon.
I appreciate for your time.
Thanks
# August 9, 2006 3:17 PM

Tonny said:

Hi, I'm moving an old conventional .asp application from iis5/w2k to iis6/win2003 and think that i have similar troubles as the .net scenario.

Cmd.exe can start an .exe or .com but when it comes to scripts (.cmd .bat) nothing happens. Not even an error message.

A sample asp code:
 Dim WSH
 Set WSH = server.CreateObject("Wscript.Shell")
 'RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C C:\foo\calc.exe" ' Works perfectly
 RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C C:\foo\calc.cmd" ' Script does not start
 'RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C C:\WINDOWS\SYSTEM32\calc.exe" ' Actually works
 'RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C whoami > C:\foo\hello.txt" ' Writes "NT Authority/NETWORK SERVICE"
 Run = WSH.Run(RunString, 0, false)

I'll probably end up writing a .exe that does what the .cmd script does.
# August 21, 2006 7:06 AM

Tonny said:

Hi again.

It turns out that my colleague had the exact same cmd.exe problem as me and i suspect the same goes for .net. Microsoft sended a trace/debug tool to him and asked him to create some logs. Appearantly this cmd.exe behavior isn't intended.

Workaround 1:  Make the webuser member of local administrators
Workaround 2:  Call a .vbs instead and let it call the cmd.exe

Of course don't use solution 1 for anonymous access (IUSR, IWAM, Network service). Here's a sample for my .vbs workaround:

Dim WSH, ErrorLevel
Set WSH = CreateObject("Wscript.Shell")
RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C C:\foo\MyScript.cmd" & _
" """ & wscript.arguments.item(0) & """" & _
" """ & wscript.arguments.item(1) & """" & _
" """ & wscript.arguments.item(2) & """" & _
" """ & wscript.arguments.item(3) & """"
ErrorLevel = WSH.Run(RunString, 0, false)
Set WSH = Nothing
Wscript.Quit ErrorLevel

Hope this can be of some inspiration to the asp.net problem.
# August 22, 2006 4:08 AM

Dennis said:

Passing parameters to a batch file

This is the first thing that came to my mind after running the cool solution.

the trick was devised from the code itself: if you can write to input stream  the command line from the batch file, why not write a command with a batch file  + parameters. I e

 System.IO.StreamWriter sIn = proc.StandardInput;

       // Write a line with batch file and parameters to standard input

       sIn.WriteLine("build.bat "  +  param);

...

Thus a bat file with

dir %1

command can be controlled with parameters (/b /s /? etc)

http://localhost:3206/VisualStudio/Default.aspx?param=/b

The result is

C:\_dennis\VisualStudio>dir /b

App_Data

build.bat

Default.aspx

Default.aspx.cs

# August 28, 2006 9:27 AM

Dino said:

Can someone tell me if the same issue exists with classic ASP under SBS2K3? And perhaps provide an example?

I am trying to run commands executables and batch files etc from classic asp and seem to be getting the same issues "Access denied" etc, I've tried the IUSR_ permissons thing but not had any luck yet, will have another go, and alter webconfig as well (first time i read that advice was here ;).

Actually one problem is I don't seem to be able to run a batch file from the command line at all? I can create it, click it in file explorer, and it runs fine, but if I open a command prompt, navigate to that directory, and type its name I get " 'test.bat' is not recognized as an internal or external command, operable program or batch file." So what going on here? Why cant I just run the batch file from the command line?

Many thanks for any help.

# September 9, 2006 9:03 AM

Dino said:

Ok have the batch file running from command line now! but having made the relevant IUSR permission changes, I can access the batch file from asp but it does not actually execute. For example i have a simple batch file that just echos some text to a text file (IUSR has read execute permisssions to the batch file and cmd.exe and full permissions to the text file). If intentionally use the wrong batch filename i get the appropriate error, now with teh correct batch file name i get no error, but equally no execution, nothing appears in the text file?

# September 9, 2006 9:52 AM

Samir said:

Dino, did you resolve it yet? I have the same problem...

# September 12, 2006 2:30 PM

Gear said:

God, I've been struglying with it since 2 days now.

I did everything imaginable to make ASP.NET 2.0 execute a simple batchfile and I always get Access Denied

I tell you,  IIS, ASP.NET ACCOUNT, Impersonation, URLSCAN, Permissions etc...etc...etc, all you can imagine have been tested.  So what else now

Windows 2000 server running IIS5.0

ASP.NET 2.0.50727

C# app which uses Process.Start() to start the batch file

Always get Access Denied.

BUT.......... I can copy files to the directory, Create file to the directory, can do a lot of things but not executing a simple batch file

Yeah right

geardoom3@gmail.com

# September 20, 2006 2:17 PM

Mahesh said:

# September 22, 2006 7:55 AM

Gennady said:

When ASP.NET is running under IIS 6 (Windows 2003) in native mode, the IIS 6 process model is used and settings in this section (<processModel from %windir%\Microsoft.NET\Framework\v1.1.4322\CONFIG\ machine.config) are ignored.  Please use the IIS administrative UI to configure things like process identity and cycling for the IIS worker process for the desired application.

If you change it to Local System for Application Pull in IIS and for "ASP.NET State Service" service account in services you will be able to run anything from ASP.NET

# September 27, 2006 11:38 PM

Maurilio Martini said:

Great Stuff!! [}}:-))

# October 10, 2006 4:15 AM

Mick T said:

I've been messing with this sort of thing so I can remotely do things like opening an MP3 or running an EXE. What I would like is to be able to have a window pop up on my screen (the servers screen) and be able to send keys to it through ASP.Net but the process belongs to the ASPNET user not the user logged in. I'm using XP SP2.

Is there any way for me to either log on as the ASPNET user or have the process belong to the logged in user (or some other way).

Thanks

Mick

# November 16, 2006 4:03 PM

Lynda said:

The information here is great.  I used it to successfully run a bat file from CMD.exe for both XP Pro and Server 2003.  I am having one issue and would appreciate anyone's thoughts and suggestions on how to resolve.

My web application runs a package software which can be started from command line.  I saved this line as my bat file.  When I double click the bat file on Server 2003, the package runs indicated with the creation of an output file.  When I run it from my web app, the name of the software shows in Task Manager but the output file is not created. When I run my web app on my XP pro device native (http:\\localhost\...), the process works and the output file is created.  I have Visual Studio installed on my XP Pro device.

To confirm that the process is working on Server 2003, I wrote another bat file that copies one file to another.  I ran that bat file from web application on Server 2003 and the copied file is created.  It appears that this code is working on Server 2003.

What would cause this to not work on Server 2003 for that package software?  Any suggestions on where to look or how to resolve this issue would be appreciated.

Thanks!

# December 4, 2006 2:32 PM

DINESH said:

DEAR ALL,

I HAVE WRITTEN A CODE IN VB TO EXECUTE AN EXE FILE THE CODE IS AS FOLLOWS

       'Create process to create a user in Linux machine

       Dim myProcessStartInfo As New ProcessStartInfo()

       myProcessStartInfo.WorkingDirectory = "C:\"

       myProcessStartInfo.FileName = "c:\plink.exe"

       myProcessStartInfo.RedirectStandardOutput = True

       myProcessStartInfo.RedirectStandardInput = False

       myProcessStartInfo.UseShellExecute = False

       myProcessStartInfo.Arguments = "-pw " & Login1.Password & " " & Login1.UserName & "@192.168.116.77 ls "

       'Start the process

       Dim myProcess As Process

       Dim myStreamReader As IO.StreamReader

       myProcess = Process.Start(myProcessStartInfo)

       myProcess.WaitForExit(2000)

       If myProcess.HasExited Then

           e.Authenticated = True

           myStreamReader = myProcess.StandardOutput

           Dim myString As String = myStreamReader.ReadToEnd

           Label1.Text = myString

           Session("UserName") = Login1.UserName

           Session("Password") = Login1.Password

           myStreamReader.Close()

       Else

           e.Authenticated = False

           Label1.Text = "Could Not Completed in Allocated Time Slot !!!"

           myProcess.Kill()

       End If

       myProcess.Close()

I am Executing a plink.exe file this works 100% perfectly in "View in Browser" mode but wen i execute it like "http://localhost/.....aspx" it says "Could Not Completed in Allocated Time Slot !!!" This is really really frustrating can someone please help.

Further I have added <identity impersonate="true"/> in my web.config and in IIS document Security I have ticked allow anonymus access and given ASPNET Administrator level authority What Else I can do other Than hang my self !!!

# December 15, 2006 12:31 AM

Naags said:

Hi,

i was trying to run an application(for e.g., notepad) thru the batch file.But my application hangs, i could see the notepad process running in the task manager, but i could not see the command window or notepad.

If my batch file has del or copy command it works eventhough i could not see the command window.

i have set integrated windows authentication and identity impersonate=true.

could u please shed a light on this

# December 16, 2006 3:45 AM

Code Smith said:

Hi,

i was trying to run an web application(for e.g., notepad) thru the batch file which developed using C#, asp.net.But my web application hangs, i could not see the command window or notepad when running from IIS Virtual Directory (http://localhost/app/filename.aspx).

i have set integrated windows authentication and identity impersonate=true.

could u please shed a light on this

Thanks

# December 16, 2006 3:47 AM

Dinesh said:

Hi Guys,

I found an answer that would help most of you I think, It works for me. You give the following command before starting the process.

Dim _password As New System.Security.SecureString

Dim password As String

password = <Your Password As String>

'This Part is important cause you cannot directly assign string variable to security string

       For Each c As Char In password

           _password.AppendChar(c)

       Next

       Dim myProcessStartInfo As New ProcessStartInfo()

       myProcessStartInfo.LoadUserProfile = True

       myProcessStartInfo.LoadUserProfile = True

       myProcessStartInfo.UserName = "Administrator"(Any User Name in Server)

       myProcessStartInfo.Password = _password

# December 17, 2006 9:57 PM

Topcat said:

Good job! this is exactly what I needed.

# January 3, 2007 3:43 PM

Jeff said: