Reputation: 2472
I have a procedure which I borrowed and modified shown below. Basically the problem is that after some amount of files, the program will crash. I traced it to this procedure. Inevitably the document itself proved to be fine, so it is something about the repeated opening and closing of word docs which is causing issues. And it's random, sometimes it will process 100 files, sometimes 800. Anyone have any thoughts? When I run it in the debugger I do not see any errors generated. The program just stops processing files and becomes unresponsive. Is there some garbage collection that I am missing? How can I tell if there is a memory leak?
private string readFileContent(string path)
{
string docstring = "";
Word.ApplicationClass wordApp = new Word.ApplicationClass();
object file = path;
object nullobj = System.Reflection.Missing.Value;
Word.Document doc = wordApp.Documents.Open(
ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj);
try
{
SProc.Println("Created word doc instance");
//doc.Clipboard.Clear();
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
SProc.Println("Copied text to clipboard");
//System.Threading.Thread.Sleep(500);
IDataObject data = Clipboard.GetDataObject();
docstring = data.GetData(DataFormats.Text).ToString();
txtFileContent.Text = docstring;
}
catch ( ConfigurationErrorsException e)
{
SProc.Println("Word Error:" +e.ToString());
}
finally
{
doc.Close(ref nullobj, ref nullobj, ref nullobj);
wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
}
return docstring;
}
Upvotes: 1
Views: 519
Reputation: 26505
Another suggestion:
Create the Word.ApplicationClass once and use it for the life of your application, I doubt you really want to start it and close it 800 times for 800 files.
Upvotes: 3