Wednesday 25 July 2012

C# Process.Start

Starts a process resource and associates it with a Process component.
Example: call external application to view documents and web pages. It also executes EXE programs and external command line utilities.

Program that opens directory [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
     //
     // Use Process.Start here.
     //
      Process.Start("C:\\");
    }
}

Program that opens text file [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
     //
     // Open the file "example.txt" that is in the same directory as
     // your .exe file you are running.
     //
      Process.Start("example.txt");
    }
}

Program that searches Google [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
      // Search Google.
       Process.Start("http://google.com/");
    }
}

Program that starts WINWORD.EXE [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
     // A.
     // Open specified Word file.
     OpenMicrosoftWord(@"C:\Users\Sam\Documents\Gears.docx");
    }
    /// <summary>
    /// Open specified word document.
    /// </summary>
    static void OpenMicrosoftWord(string f)
    {
      ProcessStartInfo startInfo = new ProcessStartInfo();
      startInfo.FileName = "WINWORD.EXE";
      startInfo.Arguments = f;
      Process.Start(startInfo);
    }
}

Program that runs EXE [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
      LaunchCommandLineApp();
    }
    /// <summary>
    /// Launch the  application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
      // For the example
      const string ex1 = "C:\\";
      const string ex2 = "C:\\Dir";

      // Use ProcessStartInfo class
      ProcessStartInfo startInfo = new ProcessStartInfo();
      startInfo.CreateNoWindow = false;
      startInfo.UseShellExecute = false;
      startInfo.FileName = "myprog.exe";
      startInfo.WindowStyle = ProcessWindowStyle.Hidden;
      startInfo.Arguments = "-f d " + ex2;

 try
 {
     // Start the process with the info we specified.
     // Call WaitForExit and then the using statement will close.
     using (Process exeProcess = Process.Start(startInfo))
     {
       exeProcess.WaitForExit();
     }
 }
 catch
 {
     // Log error.
 }
    }
}