Pregunta

I have this small piece of code (easy to try):

class Program
{
    static void Main(string[] args)
    {
        List<string> paths = new List<string>() { "1.docx", "2.docx", "3.docx", "4.docx" };

        foreach (string path in paths)
        {
            string path2 = @"Path\to\those\files" + path;

            Process process = new Process();
            process.StartInfo = new ProcessStartInfo(path2);
            System.Diagnostics.Debug.WriteLine("~>" + path2);
            process.Exited += (s1, e1) => process_Exited(path2);
            process.EnableRaisingEvents = true;
            process.Start();
        }

        while (true) { }
    }

    static void process_Exited(string path)
    {//<~ breakpoint here

    }
}

What is happening is sometimes, the breakpoint is hit moments after I start the application despite it having to wait for the processes to be exited one after another. It is always the last file of all, be it 2 files, 3 files, 4 files or more. The only time the breakpoint is never hit prematurely is when paths contains only one file. (By the way, maybe I could not care much about this strange behaviour, but when I really exit the .docx file (the last one from the paths list), the breakpoint is not hit.

Why is this (process sometimes exiting prematurely) happening and how to prevent that?

UPDATE: I just noticed it is not necessarily the last of files in paths, sometimes it is random one.

¿Fue útil?

Solución

Eventually, unable to solve the primary issue, I ended up using NetOffice:

NetOffice.WordApi.Application wordApp = new NetOffice.WordApi.Application();
wordApp.Visible = true;
NetOffice.WordApi.Document doc = wordApp.Documents.Open(path);

which solved the premature closing.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top