Hello I know how to open and get plain text from a word file for a bit of code. However I am having a bad effect occur from this. The word doc becomes locked and I am not aware how to de allocate whatever is locking it. What I ultimately want would like to open a file that will be in a UNC path and read part of it, whether someone else has it open or not, parse lines from it, close it, don’t save anything or lock the file. The closest I can get is I can open a file, parse it, it will lock, but when I open it and close it(same machine running the code) it magically unlocks it.
I know almost nothing on COM so I hunted for a while and found something out about the Marshall object and added that. I have tried to turn on and off the reference ‘ReadOnly: True’, ‘ReadOnly: False’. I feel there is just something simple I am missing so I thought I would ask here. Any suggestions feel free, I am coding in .NET 4.0 so you don’t have pass in all those annoying obj = null, obj = null for opening the Doc.
public static string ReadWordDoc(string loc)
{
Word.Application wordApp = new Word.Application();
Word.Document Doc = wordApp.Documents.Open(loc, ReadOnly: true);
sb = "";
foreach (Word.Paragraph objParagraph in Doc.Paragraphs)
{
try
{
sb += objParagraph.Range.Text + "\n";
}
catch (Exception ex)
{
throw ex;
}
}
return sb;
Doc.Close(SaveChanges: false);
Marshal.ReleaseComObject(Doc);
wordApp.Quit(SaveChanges: false);
}
I figured it out for some reason a lock was being kept. I made sure I quit the Word app with ‘Do Not Save Changes’ as well as running the Garbage Collector as well. It may be a little overkill but it essentially ensures that no lock is left on my file I am targeting.