I have a WinForms application and I am looking for a way to do the following:
- Click link to create a Word document from a BLOB in the database and open it.
- Block the WinForms application until Word is closed.
- Handle when Word is closed, check if the document was changed, and persist changes to the database.
The problem I am having is not creating the Word document and opening it, but it is hooking to the Word process to know when Word has closed. Is there some libraries to look at for doing this or any tutorials that would show how to accomplish this task?
Please see accepted solution, but here is the code I used to complete my task:
protected static string FilePath { get; set; }
public static void DisplayDocument(byte[] documentBytes, string filePath)
{
FilePath = filePath;
if (documentBytes == null) return;
if (!Directory.Exists(TEMP_FILE_DIRECTORY))
Directory.CreateDirectory(TEMP_FILE_DIRECTORY);
if (File.Exists(FilePath)) File.Delete(FilePath);
try
{
FileStream fs = new FileStream(FilePath, FileMode.Create);
fs.Write(documentBytes, 0, Convert.ToInt32(documentBytes.Length));
fs.Seek(0, SeekOrigin.Begin);
fs.Close();
ProcessStartInfo psi = new ProcessStartInfo(FilePath);
Process process = Process.Start(psi);
process.EnableRaisingEvents = true;
process.Exited += process_Exited;
process.WaitForExit();
}
catch (Exception e)
{
MessageHandler.Show(e.Message, Strings.ErrorOpeningFile);
}
}
private static void process_Exited(object sender, EventArgs e)
{
FileInfo fileInfo = new FileInfo(FilePath);
if(fileInfo.CreationTime.CompareTo(fileInfo.LastWriteTime) < 0)
Debug.WriteLine("File updated, perform database upload here.");
}
You can wait for a process to close using the following code:
when word will close, you can check if the file is modified and store it in database.