开发者

How to start a System.Diagnostics.Process in C#?

when i run this code :

        Process printjob = new Process();
        printjob.StartInfo.FileName = "file.html";
        printjob.StartInfo.UseShellExecute = true;
        printjob.StartInfo.Verb = "print";
        printjob.StartInfo.CreateNoWindow = true;
        printjob.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        printjob开发者_StackOverflow社区.Start();

this exception is thrown:

"No application is associated with the specified file for this operation"

what should i do?


The following code snippet should work, but it does have an issue that might be a deal breaker (continue reading for an explanation):

static void Main(string[] args)
{
    string pathToFile = "...";
    var processStartInfo = new ProcessStartInfo(); 
    processStartInfo.Verb = "print";
    processStartInfo.FileName = pathToFile;     

    var process = Process.Start(processStartInfo);
    process.WaitForExit();
}

The only problem with the code above is that it will show the print dialog. I was unable to find a way to supress it, and it seems to be an issue (or feature) specific to printing HTML files.

There's an ugly workaround if you can tolerate having the print dialog appearing for a second or so, and that is to simulate sending the "enter" key to the print dialog through code. The easiest way to do that is to use the System.Windows.Forms.SendKeys class, specifically the SendWait method.

So the revised code snippet will look like the following:

static void Main(string[] args)
{
    string pathToFile = "...";
    var processStartInfo = new ProcessStartInfo(); 
    processStartInfo.Verb = "print";
    processStartInfo.FileName = pathToFile;     

    var process = Process.Start(processStartInfo);

    System.Threading.Thread.Sleep(1000);
    System.Windows.Forms.SendKeys.SendWait("{ENTER}");

    process.WaitForExit();
}

The call to the Sleep is necessary to ensure that the print dialog is fully loaded and ready to receive user input before sending the key press.

HTH


On your computer, no application is associated with the file-type ".html". If you're trying to view it in a web browser, consider starting iexplore.exe (for example, to launch internet explorer), and then include the file.html as a parameter.

For example:

Process.Start("IExplore.exe", @"C:\myPath\file.html");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜