Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]

Process.Start() Quips

It is more than a common requirement to be able to start another process from executing code. For instance, you might want to execute a batch file, run a command line utility of sorts, and so on. This is facilitated in the BCL through System.Diagnostics.Process class, more specifically, the Start method.

Process.Start("Notepad.exe");

You can also specify startup information like FileName, Argument, WindowStyle and so on, through the instance of another class called ProcessStartInfo.

ProcessStartInfo oStartInfo = new ProcessStartInfo();
oStartInfo.FileName = "Notepad.exe";
oStartInfo.Arguments = "MyWork.txt";
Process.Start(oStartInfo);

Simple. But there is a catch here. The instance of ProcessInfo bears a property called UseShellExecute. A value of true for this property would mean that the windows shell is used to start a process, and this is the default value. Therefore, you wouldn’t be able to extract the output or provide an alternative input for the process to be executed. This feature would be required, for instance, if you want to capture the output of a SQL script execution through osql.exe or as another example, the output of a command-line setup. So, to make this work, we need to set UseShellExecute to false and then, as required, set RedirectStandardInput (default is keyboard), RedirectStandardOutput (default is monitor), RedirectStandardError (default is monitor) properties to true. One thing to keep in mind, in this case is that, you should specifiy the full path of the executable or the path must be listed in the PATH environment variable. The code snippet given below captures the execution of a batch file and writes it to a log file:

Process runCmd = new Process();
runCmd.StartInfo.FileName = "RunBatch.bat";
runCmd.StartInfo.UseShellExecute = 
false;
runCmd.StartInfo.RedirectStandardOutput = 
true;
runCmd.Start(); 

FileStream fs = 
new FileStream("OutPut.log",FileMode.Append);
StreamWriter sw = 
new StreamWriter(fs);
sw.Write(runCmd.StandardOutput.ReadToEnd());
runCmd.WaitForExit();

sw.Close();
fs.Close();

Another simple tip is that, when UseShellExecute is true, you can start any document if its file type is associated with an executable that has the default action as open. For e.g. The following code launches test.txt in default text editor (notepad on my m/c)

ProcessStartInfo psi= new ProcessStartInfo(@"C:\test.txt");
Process.Start(psi);

You can say also associate verbs like Print etc.

ProcessStartInfo psi= new ProcessStartInfo(@"C:\test.txt");
psi.verb = "Print";
Process.Start(psi);

As another example, the following code launches the URL provided in the default browser.

Process.Start("http://www.microsoft.com");

Posted: Oct 23 2004, 05:15 PM by Manoj G | with 25 comment(s)
Filed under:

Comments

Manoj G said:

Hi,
My application has registered a file type with it so if i double click its file in Windows Explorer, the application is launched.

Now once I have an applicaiton launched, I would like that when next time some other file of same application is double-clicked, instead of loading a new instance of application is loaded, the same old instance is launched showing contents of new file.

How do I do that? It would be a great help if you can mail me the solution on my email address ginve above in the Name field.


Thanks.
# December 22, 2004 1:18 PM

Manoj G said:

Hi

I want to start a console application which takes an command line argument from the windows service.

The code is given below
ProcessStartInfo processStartInfo = new ProcessStartInfo('abc.exe', '434');
processStartInfo.WorkingDirectory = Environment.CurrentDirectory;
processCollection.Add(Process.Start(processStartInfo), false);

The above throws an error :

{System.InvalidOperationException}
System.SystemException: {"The Process object must have the UseShellExecute property set to false in order to use environment variables."}

The console application is in the same path as the windows service.
To solve this problem if i use processStartInfo.StartInfo.UseShellExecute = False ;
stmt will it solve the purpose ???

Pls reply to sugaz@rediffmail.com

Thanks
Sugavaneswaran S






# January 13, 2005 10:57 AM

Manoj G said:

Sugavaneswaran

Simply, don't fill processStartInfo.WorkingDirectory. The started process will default start in current dir.
# January 27, 2005 4:24 AM

Manoj G said:

Hi..

I create a window service and override the onStart method with these lines:

eventLog1.WriteEntry("testttt");
try
{
ProcessStartInfo psi= new ProcessStartInfo(@"E:\test.txt");

Process.Start(psi);
eventLog1.WriteEntry("started");
}

catch(Exception e)
{
eventLog1.WriteEntry(e.ToString());
}

I started the service and check the event viewer. Two log entries is created, "tessstt" and "started" is there, but the test.txt file never appear...

I have tried to start the process( E:\test.txt) in console application and it works fine.

Is there any difference and how to start a process in the window service

Thank u in advance for the help ,
Marissa
# February 27, 2005 8:35 PM

Manoj G said:

Hi
how to start the IE.exe from within a C# application with a specific location, hight and width for example?
Thanks
# March 4, 2005 7:42 PM

Manoj G said:

I have the same problem with windows service. When i run Process.Start("notepad.exe"), i cant open a notepad window but the i see the process running in task manager. Pls email me at prasad32377@yahoo.com if you have a solution.
# April 15, 2005 4:55 AM

Manoj G said:

You need to allow services explicitly to interact with the desktop if you want to display a notepad when you execute Process.Start("notepad.exe") from windows service. Inorder to do this, right click on the service that you are running and click on properties. Under LogOn tab, check "Allow Service to interact with Desktop". This should do the trick. If you have any questions, email me to prasad32377@yahoo.com
# April 15, 2005 5:32 AM

Manoj G said:

Hi

I try to run a bat file in aspx but It doesn't work. I tested with imporsonation but still the process uses ASPNET account. Do you know how can I specify which user the process should use?

thank you
# April 26, 2005 8:01 PM

Manoj G said:

For anyone running anything behind a windows service, you have to allocate a console handle in order to see the window. An easy way to do this is to select the "Interact with desktop" setting on the service. Hope that helps...
# May 20, 2005 10:28 PM

Manoj G said:

> For anyone running anything behind a windows service,
> you have to allocate a console handle in order to see the
> window. An easy way to do this is to select the "Interact
> with desktop" setting on the service. Hope that helps...

Is there any way to have this option as the default using a .Net setup project?

It would be annoying to expect an end user to have to modify a service after an install.
# July 18, 2005 1:11 AM

Manoj G said:

Ken:

The ServiceInstaller class doesn't offer you an easy way to do this, oddly enough. You have to set the registry key yourself. Here's a code snippet that you can put in an overridden Install() method of your project installer class (after calling base.Install())

Microsoft.Win32.RegistryKey ckey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + this.serviceInstaller1.ServiceName, true);

if(ckey != null)
{
if(ckey.GetValue("Type") != null)
ckey.SetValue("Type", ((int)ckey.GetValue("Type") | 256));
}

You do a bitwise OR with 256 on the Type value. That sets that little flag!
# August 4, 2005 10:21 PM

Manoj G said:

I have some problems with redirecting StandardOutput of process under windows service.

Here is code that starts the process:

Dim proc As Process = New Process
Dim output As String = ""

proc.StartInfo.FileName = "backup.cmd"
proc.StartInfo.Arguments = args
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.UseShellExecute = False
proc.StartInfo.CreateNoWindow = True

proc.Start()
output = proc.StandardOutput.ReadToEnd()
proc.WaitForExit()

proc.Close()

Return output

Can you recommend something to solve this problem ?
# August 17, 2005 5:17 PM

Manoj G said:

Ops... Just forgot to mention the problem itself.

In case that code executes under regular application everything is ok, but when it is executed under windows service output is empty

May be processes under services has some restrictions ?
# August 17, 2005 5:28 PM

Manoj G said:

Hi,

ive got similar problems that the ones above. I have a Windows Service which downloads a msi file from a server. After downloading the file it has to be installed/executed. I'm not able to have it installed properly. The problem is, that the Directories are created correctly and the files are also copied to the right place, but somehow the Application is not installed properly. It doesnt appear in Add/Remove Programs and the entry into the startmenu is also missing.

If i run the msi file manually within a shell using msiexec or using directly the msi file everthing works great.

Does anyone know what the problem is here? Any help is greatly appreciated.

Thanks in advance

Jens
# August 25, 2005 8:38 PM

uuyytt said:

I have the same problem with windows service. When i run Process.Start("notepad.exe"),event I allow services explicitly to interact with the desktop. PS. This problem occur only on windows 2003
# October 4, 2006 3:35 AM

uuyytt said:

I have a Windows service from which I want to start Internet Explorer with a particular URL as an argument. It can work well except when I run it on windows 2003 I allowed services explicitly to interact with the desktop and I tested with imporsonation but still not work. I don't know why my code (shown below) doesn't work. I know that IExplore.exe starts as I can see it in my task manager, but it is not visible. Can anyone explain what is happening? My code: protected override void OnStart(string[] args) { Process p = Process.Start(@"C:\Program Files\Internet Explorer\IEXPLORE.EXE", m_strURL); }
# October 4, 2006 4:09 AM

Nits said:

I am trying to print a pdf file using the following code... It does not throw an error but does not print either when the applicationo s hosted in a web server and is executed from a client machine Please help... System.Security.SecureString secureData = new System.Security.SecureString(); secureData.AppendChar('B'); secureData.AppendChar('l'); secureData.AppendChar('a'); secureData.AppendChar('c'); secureData.AppendChar('k'); ProcessStartInfo process; Process adobeProcess; Boolean isRunning; DateTime startTime; DateTime timeOutTime; string arguments = "/t" + " " + filename + " " + printerName; process = new ProcessStartInfo(acrobatReaderPath, arguments); process.CreateNoWindow = true; process.RedirectStandardOutput = true; process.UseShellExecute = false; process.WindowStyle = ProcessWindowStyle.Hidden; adobeProcess = new Process(); adobeProcess.StartInfo = process; adobeProcess.StartInfo.UserName = System.Configuration.ConfigurationManager.AppSettings['reportusername'].ToString(); adobeProcess.StartInfo.Password = secureData; adobeProcess.StartInfo.Domain = 'itlinfosys'; startTime = DateTime.Now; adobeProcess.Start(); Thanks
# November 4, 2006 12:10 AM

Jay said:

Hello MVPs,

I have a problem where opening a word document using Process.Start("filename") throws a Win32Exception as below

See the end of this message for details on invoking

just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************

System.ComponentModel.Win32Exception: Access is denied

  at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)

  at System.Diagnostics.Process.Start()

  at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)

  at System.Diagnostics.Process.Start (String fileName)

I tried using Regmon to track any registry access denied, but could not find any problem,

or may be there is some other error i should be looking for.

This error occurs only on specific machines (laptops) and works well for other machines.

Any help on this topic is highly appreciated :)

Thanks,

Jay

# March 14, 2007 10:00 PM

carry said:

i m facing the same problem..my process is not running any application in windows service and run under normal applicatin..can u tell me the solution please..i need it urgent

# April 19, 2007 10:43 PM

Dave said:

In a response to Ken, and also to fix the issue, I would like to know why I have to tick and untick the Interact checkbox to make it work. (The code does make it ticked but as no effect).

I've also noticed other ControlSet in the registry,

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\MYSERVICE

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Services\MYSERVICE

Should I change the value for these also.  

Why do I need to go under services and untick, tick again, apply to make it work ???

floyd us 27 a t hotmail d o t com

Thanks.

# July 20, 2007 9:37 AM

kamran said:

winservice starts the process (Application) but does not bring it to interface. i ve checked Interact with desktop

but doesn't work

using win-XP

VS-2003

# August 26, 2007 6:34 AM

roberto said:

I have a problem with windows service. When i run Process.Start("iexplore.exe"), i cant open a iexplore window but the i see the process running in task manager. This services running under windows server 2003, and have checked Interact with Desktop, but doesnt work. My email is roberto@t2o.es . If someone can help me, send me a email please. Thank you for you colaboration.

# September 26, 2007 6:37 AM

Neeraj said:

Hi,

I have the ollowing code running for runing a console application:

Process myProcess = new Process();

           ProcessStartInfo info = new ProcessStartInfo(appName);

           myProcess.StartInfo = info;

           myProcess.StartInfo.UseShellExecute = false;

           myProcess.StartInfo.RedirectStandardOutput = true;

           myProcess.StartInfo.RedirectStandardInput = true;

           myProcess.Start();

           myProcess.WaitForExit();

Here I am passing the names of different console applications in the ProcessStartInfo.

My Problem is that the console application starts, but within a second closes, though when I run this application as a standalone, it runs properly.

Please Help somebody

# October 17, 2007 1:30 AM

Zeina said:

Dear,

I have a batch file that runs Adobe.exe application. Executing this batch file from a Windows Application worked fine and the output of the Batch successfully achieved whereas the same code called from an ASP.NET application doesn’t work. The exe is displayed in the Task Manager but doesn’t execute the code it should and the user runing this service is the Administrator.

Apparently it is a security issue sine the problem occurs when hosting the application in IIS but I have tried working with all the permissions and it didn’t work. The Identity of the pool of the web site is Configurable with the System Administrator Credentials.

Many have the same problem but none has listed the solution. This is very urgent, so pleaseeeeeeeeeeeee help :(

Thank you,

Zeina

# November 2, 2007 10:52 AM

Rohit said:

Does any one know a way in which the new process just created can be debugged (in Visual studio) ?

# January 9, 2008 12:23 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)