Search code examples
.netms-wordshellexecute

Process.Start with 'UseShellExecute = true' doesn't return for corrupt word documents


I am trying to print pdf, ppt, and word documents from my windows service using ShellExecute.

Process printingProcess = new Process
                        {
                            StartInfo =
                                {
                                    FileName = filePath,
                                    WindowStyle = ProcessWindowStyle.Hidden,
                                    CreateNoWindow = true,
                                    UseShellExecute = true,
                                    Verb = "Print"
                                }
                        };
printingProcess.Start();

This works in most cases. But for word documents that are corrupt, the Process.Start method never completes and the service hangs.

Basically, word pops up the "bad document! repair" dialog. I want the service to identify that word is not playing nice and kill the process and proceed with the next document in its queue.

What should I do?

[UPDATE]

Guys, here is the code to reproduce the issue:

static void Main(string[] args)
{
    string filePath = @"d:\corruptdocument.docx";

    PrintDocument(filePath);

    Console.WriteLine("Completed!");
    Console.ReadKey();
}

private static void PrintDocument(string filePath)
{
    Process printingProcess = new Process
                                {
                                    StartInfo =
                                        {
                                            FileName = filePath,
                                            WindowStyle = ProcessWindowStyle.Hidden,
                                            CreateNoWindow = true,
                                            UseShellExecute = true,
                                            Verb = "Print"
                                        }
                                };
    using (printingProcess)
    {
        Console.WriteLine("Starting process...");
        printingProcess.Start();
        Console.WriteLine("Completed start...");
    }
}

And here is a screenshot : http://twitpic.com/23jwor


Solution

  • Okay Guyz, here is what I found out!

    ShellExecute for word uses DDE. So the process.Start() method returns only after the command is complete (in my case, "printing the document"). [Not sure if this is accurate, but atleast that is my experience with word]

    So what are our options?

    1. As @Hans mentioned, use COM interop.
    2. Run the printing job in a seperate thread and wait for the thread to complete for a predefined interval and terminate the corresponding word process after this interval.

    I chose option 2 as I was dealing with other document types like PDF,PPT and I was too lazy to change the implementation! :)