Exited event of Process is not rised?

Posted by Kanags.Net on Stack Overflow See other posts from Stack Overflow or by Kanags.Net
Published on 2010-03-17T15:11:54Z Indexed on 2010/03/17 15:31 UTC
Read the original article Hit count: 204

Filed under:

In my appliation,I am opening an excel sheet to show one of my Excel documents to the user.But before showing the excel I am saving it to a folder in my local machine which in fact will be used for showwing.

While the user closes the application I wish to close the opened excel files and delete all the excel files which are present in my local folder.For this, in the logout event I have written code to close all the opened files like shown below,

Process[] processes = Process.GetProcessesByName(fileType);

                foreach (Process p in processes)
                {

                    IntPtr pFoundWindow = p.MainWindowHandle;
                    if (p.MainWindowTitle.Contains(documentName))
                    {
                        p.CloseMainWindow();
                        p.Exited += new EventHandler(p_Exited);                            
                    }                       
                }

And in the process exited event I wish to delete the excel file whose process is been exited like shown below

void p_Exited(object sender, EventArgs e)
    {
        string file = strOriginalPath;
        if (File.Exists(file))
        {
            //Pdf issue fix
            FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
            fs.Flush();
            fs.Close();
            fs.Dispose();
            File.Delete(file);
        }
    }

But the problem is this exited event is not called at all.On the other hand if I delete the file after closing the MainWindow of the process I am getting an exception "File already used by another process".

Could any help me on how to achieve my objective or give me an reason why the process exited event is not being called?

© Stack Overflow or respective owner

Related posts about c#