In my application, I open an excel sheet to display one of my Excel documents to the user. But before showing excel, I save it in a folder on my local machine, which will actually be used for showwing.
While the user is closing the application, I want to close the open excel files and delete all the excel files that are in my local folder. To do this, in the logout event, I wrote code to close all open files, as 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 completed process, I want to delete the excel file whose process is completed, as shown below
void p_Exited(object sender, EventArgs e)
{
string file = strOriginalPath;
if (File.Exists(file))
{
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
fs.Flush();
fs.Close();
fs.Dispose();
File.Delete(file);
}
}
But the problem is that this outgoing event is not called at all. On the other hand, if I delete a file after closing the MainWindow process, I get an exception "The file is already being used by another process."
- , , , ?