Click here to Skip to main content
15,920,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written following Code to edit bookmarks of Word document., as document is generated doc is visible but if i close the same and tried to open the same doc again the word doc gives error as :

1.Check file permissions for file/ drive.
2.make sure there is sufficient memory and disk space.


private void GenerateApplication()
{
object readOnly = true;
object repair = false;
object bookMarkName = "applicantName";
object bookMarkCompany = "firmName";
object bookMarkPost = "postName";

fielName = @"C:\Documents and Settings\All Users\Desktop\OperateWordFromC#.dotx";


objDoc = wordApp.Documents.Open(ref fielName, ref missingValuesValues, ref readOnly, ref missingValuesValues, ref missingValuesValues,
ref missingValuesValues, ref missingValuesValues, ref missingValuesValues, ref missingValuesValues,
ref missingValuesValues, ref missingValuesValues, ref missingValuesValues, ref repair, ref missingValuesValues, ref missingValuesValues, ref missingValuesValues);

objDoc.Activate();

objDoc.Bookmarks.get_Item(ref bookMarkName).Range.Text = txtApplicantName.Text;
objDoc.Bookmarks.get_Item(ref bookMarkCompany).Range.Text = txtAppliedCompany.Text;
objDoc.Bookmarks.get_Item(ref bookMarkPost).Range.Text = txtAppliedPost.Text;

string outputFile = @"C:\Documents and Settings\All Users\Desktop\ApplicationOf-" + txtApplicantName.Text + ".docx";

bookMarkName = null;
bookMarkCompany = null;
bookMarkPost = null;

Object objSaveAsFile = outputFile;
Object objFileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;

wordApp.ActiveDocument.SaveAs(ref objSaveAsFile, ref repair, ref missingValuesValues, ref missingValuesValues, ref missingValuesValues,
ref missingValuesValues, ref missingValuesValues, ref missingValuesValues, ref missingValuesValues, ref missingValuesValues,
ref missingValuesValues, ref missingValuesValues, ref missingValuesValues, ref missingValuesValues, ref missingValuesValues, ref missingValuesValues);

wordApp.Visible = true;
}
Posted

1 solution

It has been years since I've worked with Word automation in C#, but this comes to mind; see if this is relevant:

When you assign Text to an existing BookMark's Range.Text Property, that effectively removes the BookMark object, because the BookMark itself is included in the Range.

What you want to do, then, is first check if the BookMark actually exists before trying to reset it, and, then, "measure" the BookMark, create a new Range based on your measurements, then, re-create it with its new Text value; an example of this technique for VSTO circa 2006 is shown here: [^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900