Question

Running a .bat file using C# Process

Asked by: sidhuvora

Hi all,

     I am trying to run a .bat file which in turn contains a command for an application. here is my code.
--------------------
           string filepath2 = strArray[2] + "\\myCmd.bat";
        
           StreamWriter swrr = File.CreateText(filepath2);

           swrr.WriteLine("\"C:\\Program Files\\Adobe\\After Effects 6.5\\Support Files\\afterfx.exe\" -r "+path2);
                  swrr.Close();
                           
                       Process myProcess;
            myProcess = new Process();
            myProcess= Process.Start("C:\\Inetpub\\myCmd.bat");  
            myProcess.WaitForExit(240000);
            myProcess.Close();
-----------------------------

             The code creates the .bat file. And also when I double-click it or either run it from cmd.exe then it runs file and executes the command within it.

        But by using C# Process.Start(), it simply does nothing. Is anything wrong with the code? or something needs to be added to it.

       Please help me..it is urgent!!!

    Thanks
 

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-06-25 at 18:51:28ID21038777
Tags

file

,

process

Topic

C# Programming Language

Participating Experts
5
Points
50
Comments
24

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Execute .bat file
    I need to write a program that can run in the background and execute a .bat file within a unit amount of time, over and over. The main concern is having this programm execute a .bat file, how do I write a program to execute another?
  2. Open .bat file
    Hi Is there a way I can open a batch file (.bat) using code or macros in an access db. I have tried the RunApp action from a macro, but this flashes open the batch file and then it dissapears again without actually running. Cheers M
  3. Hide cmd.exe window after starting Java app from .bat file
    Hi, I am running a Java application via a batch file containing the following... "%JAVA_HOME%\java" -jar "%EOS_HOME%\dist\EuSynchronization.jar" The cmd.exe window opens, then the app starts. fine. How can I programmatically (either on the java...
  4. bat files
    Hi experts, I have created this bat. file but when I run it i get an error saying wsdl is not recognised as an internal or external command. ===========================================bat file rem StInfoProxy.bat rem bat file for creating StInfo Proxy dll re...
  5. Creating Bat file
    Hi, so I want to create a bat file witht he following lines, because I want to avoid typing these lines every time : cd .. cd .. cd UserTemp cd WorkspaceTestRegain cd CrawlerRegain the problem is that if I execute the bat, I don't have the input anymore, an...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Timbo87Posted on 2004-06-25 at 20:57:35ID: 11404015

Why not run it all through the Start method instead of using a BAT file?

Process.Start(@"C:\Program Files\Adobe\After Effects 6.5\Support Files\afterfx.exe", "-r " + path2);

 

by: drichardsPosted on 2004-06-25 at 23:49:50ID: 11404372

Timbo87's suggestion is a good one since there's nothing else going on in the batch file.

The batch file will not run directly as you originally tried because it is not executable.  It needs the command shell to run.  One way to get the batch file to run is:

Process.Start("cmd.exe", "/C C:\\Inetpub\\myCmd.bat");

This will execute the batch file and then the console window will go away.  You can use /K rather than /C if you want the console to hang around and wait for a manual close.

 

by: sidhuvoraPosted on 2004-06-28 at 09:30:38ID: 11417236

Hi all,

    I tried Timbo's option and it is not working....now I am going to try D Richard's option.

  Thanks,

 

by: sidhuvoraPosted on 2004-06-28 at 09:56:23ID: 11417557

Hey,
 
      I tried D Richard's option too and that is not working either....do you know what can be the problem....??

       Please anybody help me...what my application does is the following.

      The command should start the process with After Effects application, which runs the script file provided in 'path2'. The script runs and creates a project and saves in the same C:\Inetpub directory.

      The script runs fine when ran directly with After Effects, either from File menu or from cmd.exe...only it doesnt run with my C# application... :(

      Please help me....

 

by: drichardsPosted on 2004-06-28 at 10:04:52ID: 11417678

What error are you getting as either of the two options given should work?  Does it give you an error dialog of any sort?  Try putting a try/catch around it and see if that tells you anything.

try
{
  Process.Start(...);
}
catch (System.Exception ex)
{
  System.Windows.Forms.MessageBox.Show(ex.Message);
}

 

by: sidhuvoraPosted on 2004-06-28 at 10:29:13ID: 11418003

Hey Richard,

        It doesnt show me any error using either yours or Timbo's method.

       System.Windows.Forms.MessageBox.Show(ex.Message);     was giving me an error like Windows is not a namespace in system,eventhough i checked it is!!  so I did a Response.Write(ex.ToString()) and it returned without any error.

        And either of your method doesnt create the .bat file it just opens up cmd.exe in the TaskManager. using my above code it creates the batch file correctly but doesnt run it thereafter.. :(

       is there any other way....something like activexobject or something???? or why is it not working :(

 

by: sidhuvoraPosted on 2004-06-28 at 11:10:51ID: 11418456


 Please help me.........anybody :(

 

by: drichardsPosted on 2004-06-28 at 11:15:50ID: 11418525

You say "And either of your method doesnt create the .bat file".  That is correct as in Timbo86's solution you don't need it and I assumed that since you already have that code I didn't need to include it again.  Since you see the cmd.exe process start, you should make sure that the batch file exists before you start - put a breakpoint in your code at the Process.Start call and then go check your filesystem to make sure the batch file is there.

Also, since you are using ASP.NET (I assume so since you could do a Response.Write) you do not have access to System.Windows.  Also, the command console will not appear on the screen when you do the Process.Start, so you should not use the /K option.

 

by: sidhuvoraPosted on 2004-06-28 at 11:23:46ID: 11418627


   I am checking the directory where the bat file is suppose to be created, but it is not there that is why I said it doesnt create the batch file also...now what?

 

by: drichardsPosted on 2004-06-28 at 11:47:22ID: 11418846

I'd look at these lines:

           string filepath2 = strArray[2] + "\\myCmd.bat";
       
          StreamWriter swrr = File.CreateText(filepath2);

           swrr.WriteLine("\"C:\\Program Files\\Adobe\\After Effects 6.5\\Support Files\\afterfx.exe\" -r "+path2);
               swrr.Close();

and check 'strArray[2]' and 'path2' to be sure they have valid values.  Based on the fact the Timbo87's solution also did not work for you, my suspicion is that the value of 'path2' is not what you expect.  Other than that, I cut-and-pasted this code into a program of my own and it created the bat file no problem.  Of course I did not use strArray[2] or 'path2' they are not defined in this code snippet, so those are the two potential problems.

 

by: drichardsPosted on 2004-06-28 at 11:53:11ID: 11418896

Also, as I look at your code, you build the bat file path from strArray[2] in the first line, but then you hard-code 'C:\Inetpub\' in the process call.  If you stick with the cmd.exe invocation, you should use the 'filepath2' variable in the process start call to maintain consistency.

    Process.Start("cmd.exe", "/C " + filepath2);

or

    string params = "/C" + filepath2;
    Process.Start("cmd.exe", params);

 

by: sidhuvoraPosted on 2004-06-28 at 11:56:43ID: 11418937

ok let me try that richard...

 

by: sidhuvoraPosted on 2004-06-28 at 12:06:33ID: 11419052

ok richard,

     i see some ray of hope. this time the batch file was created and also i could see AfterFX.exe running in my taskmanager. but it didnt take the argument file and run it to make a project...

     

 

by: drichardsPosted on 2004-06-28 at 12:10:29ID: 11419086

OK, very close then.  This still points to 'path2' being incorrect.  Can you look at 'path2' in the debugger and see if its value is what you expect?  Also, does the batch file look as you expect?

 

by: sidhuvoraPosted on 2004-06-28 at 12:18:47ID: 11419163


   When I do a Response.write on path2 and filepath2, they both are correct and below is what my myCmd.bat looks like with path2 being C:\test\MyCopy.jsx which is correct.

  "C:\Program Files\Adobe\After Effects 6.5\Support Files\afterfx.exe" -r C:\test\MyCopy.jsx


    and also when I double-click on the bat file that is created at C:\test then it runs the script which again opens AfterFX.exe with script and saves the desired project. All the things that this line HAS to do.

    so basically it is not taking the argument part of the batch file.

    Do you think the batch file executes only the things withing double-quotes...
 
   should i embed the argument part also in the double quote so that my bat file looks like this

      ""C:\Program Files\Adobe\After Effects 6.5\Support Files\afterfx.exe" -r C:\test\MyCopy.jsx"

     ????
 

       

 

by: sidhuvoraPosted on 2004-06-28 at 12:26:30ID: 11419253

ok,

   i tried the second option which didnt work. i also tried the below thing which didnt work either...

   "C:\Program Files\Adobe\After Effects 6.5\Support Files\afterfx.exe" "-r C:\test\MyCopy.jsx"

  PS: I have changed my dir to C:\test instead of C:\Inetpub...i was thinking it is a asp.net dir so something going wrong becoz of that but alas..... not ...:(

 

by: drichardsPosted on 2004-06-28 at 12:51:23ID: 11419500

So your current state is that the same batch file will run fine when run manually at the command line or if you double-click on it, but will not run properly when done through Process.Start.  Is that correct?  If so, I would try Timbo87's method again and see if afterfx shows up in the task manager that way.  You could also try redirecting the batch file output to see if any information is printed out.

Process.Start("cmd.exe", "C:\\test\\myCmd.bat > C:\\test\\output.txt 2>&1");

If that still does not work properly, does afterfx create any windows as it runs?  It seems that processes started from ASP.NET behave differently.  As I mentioned, and as you have probably seen by now, the console window does not appear when executing the batch file out of ASP.NET.  Perhaps this is somehow fouling up afterfx?  Other than that, I'm about out of ideas - maybe an ASP.NET expert could help you.

 

by: sidhuvoraPosted on 2004-06-28 at 13:06:06ID: 11419681

Hi Richard,

      You are correct. the batch file runs file manually but will not run partially( only the command line part, as it opens up afterfx.exe) through the C# script.

      I tried the code above but it doesnt create any output.txt file.

      When the script is run manually, yes afterfx opens up windows while it runs. and yes the console window does not appear as it runs afterfx.exe, it can be only seen in the Task Manager.

      Please tell me if you have any other ideas.. though I am posting the same question with our conversation in ASP.NET discussion board also.

      Thank you so much Richard for going through all this with me. I am really grateful to you.

 

by: sidhuvoraPosted on 2004-06-29 at 12:37:31ID: 11429618

Hi,

    finally i have found a way.
 
     finally I have decided to use batch files and run it through a C# .cs file. So now I have a .cs file on the server that executes the batch files. basically i am using socket programming now.

    Thanks a lot.

 

by: jrasilloPosted on 2004-08-06 at 06:51:28ID: 11735432

Hey,
 I had tried to run a batch file from an aspx a long time ago, however some of the commands were not running properly (I think due to security permissions in .NET), so I decided to run every single line of code I had by itself.
Everything went well until one day I decided to add an extra executable command and ofcourse is not executing properly, can you send me a link or some example code that I can look at to see how you figure this out using socket programming.

Thanks,
Jorge

 

by: sidhuvoraPosted on 2004-08-06 at 10:21:51ID: 11737666


   I changed the design of my code again. So I am not using socked programming now.

   Now I have a server running on the IIS server machine, which monitors a folder. As soon as there are some files in the folder(which are the batch files I write out with my .aspx C# code, containing the commands i want to run), it will execute the files in the folder.

   Now regarding your problem. You know file I/O in C# so you can make batch files out of it and execute it using the following.
 

                                                                                                StreamReader sr = new StreamReader(file);
                                    string command = sr.ReadLine();

                                    ProcessStartInfo startinfo=null;
                                     Process proc=null;
      
                                    startinfo = new ProcessStartInfo();

                                     try{
                                    startinfo.FileName = "C:\\WINNT\\system32\\cmd.exe";
      
                                      startinfo.Arguments =  command;
                                      startinfo.UseShellExecute = false;
                                      startinfo.CreateNoWindow=false;
        
                                      proc = Process.Start(startinfo);
                                      proc.WaitForExit(60000);
                                      }catch(Exception ee)
                                      {
                                        Console.Write("OR Error is here: "+ee.ToString());
                                      }finally{
                                      proc.Close();
                                      proc=null;
                                      startinfo=null;
                                         }



   hope that this solves your problem..

 

 

by: RoboRubikPosted on 2005-07-21 at 12:41:30ID: 14496645

Sounds dangerous.

 

by: payal1711Posted on 2005-07-22 at 10:04:05ID: 14504536


   do you have any solution to this?

 

by: jrasilloPosted on 2005-07-24 at 19:40:34ID: 14515705

I started by giving permissions (rwx) to the file I was executing, then worked my way back. I did the same for the folder I was writing too. However as RoboRubik pointed out changing permissions might lead to security breaches :S. At the point where I had succeeded I started craeting assemblies with strong naming policies, which in turn its supposed to make it safer, keyword supposed.

here is a link that I'd suggest you take a look at:
http://www.csharphelp.com/archives/archive203.html



20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...