tags:

views:

79

answers:

3

I have one button and one textbox on form. When I click on the button, Microsoft Word is started. When the user closes Word, I want to get the file name that the user saved his work under to show up in the text box.

I am using the following code for button_click:

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files\Microsoft Office\Office12\winword.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;

System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = listFiles.StandardOutput;

listFiles.WaitForExit();

if (listFiles.HasExited)
{
    System.IO.FileInfo ff = new System.IO.FileInfo(myOutput.ToString());
    string output = myOutput.ReadToEnd();
    this.processResults.Text = output;
}
+2  A: 

I don't believe this is possible via the command line. Also, realize that, if the user opens another document, your code will not finish, since it'll wait until all of the docs are closed (the process won't end until that point).

That being said, you should be able to use the Word/Office Interop libraries, and listen to the DocumentBeforeSave and/or DocumentBeforeClose events. This should let you pull the information from the Document itself, right as it's being saved/closed.

Reed Copsey
+2  A: 

I don't think you can do this with the current code you have. ProcessStartInfo is very generic and has no knowledge of word.

I think you will want to use Visual Studio Tools for Office (VSTO) to start word. This way you have a reference to the word application and document and can get the document name.

this article should get you started http://www.c-sharpcorner.com/UploadFile/mgold/WordFromDotNet11082005235506PM/WordFromDotNet.aspx the sample code has a object called aDoc. Then after the save you can check aDoc.FullName to get the path.

olle
+1  A: 

I'm not sure whether it's possible or not because name of the saved file is an internal information that's not public for other applications. Instead in your particular case since you are using MS Word you can use Word interop to start the Word application in your application and then handle its events

Beatles1692