使用c#在ms字中添加CustomDocumentProperties时出现未指定的错误

时间:2014-04-09 09:29:23

标签: asp.net

我想使用c#将CustomDocumentProperties添加到我现有的MS Word docx文件中。 我能够打开文件,但是当我要添加CustomDocumentProperties时它会给我 以下例外。

  

{"未指定错误(HRESULT异常:0x80004005(E_FAIL))"}

当我通过初始化一个新的doc对象尝试这个时,还有一件事,它没有给我任何错误。 我用过的代码如下。如果我在这里犯了任何错误,请帮忙。

object type = Type.Missing;
Word.Application word;
Word._Document doc;
Word._Document doc1;
string filePath = "D:\\abc1.docx";
string targetFileName = "D:\\abc1.docx";

 protected void Page_Load(object sender, EventArgs e)
{
    word = new Word.Application();
    word.Visible = false;

    doc1 = word.Documents.Open(filePath, false);
    SetDocumentProperty1("Subject", "Whitepaper");
    GetDocumentProperty1("Subject", MsoDocProperties.msoPropertyTypeString);
    doc1.SaveAs(targetFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault);

    doc1.Close(false);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc1);
}
   public void SetDocumentProperty1(string propertyName, string propertyValue)
{
    object oDocCustomProps = doc1.CustomDocumentProperties;
    Type typeDocCustomProps = oDocCustomProps.GetType();

    object[] oArgs = {propertyName,false,
             MsoDocProperties.msoPropertyTypeString,
             propertyValue};

    typeDocCustomProps.InvokeMember("Add", BindingFlags.Default |
                               BindingFlags.InvokeMethod, null,
                               oDocCustomProps, oArgs);



}
private object GetDocumentProperty1(string propertyName, MsoDocProperties type)
{
    object returnVal = null;

    object oDocCustomProps = doc1.CustomDocumentProperties;
    Type typeDocCustomProps = oDocCustomProps.GetType();


    object returned = typeDocCustomProps.InvokeMember("Item",
                                BindingFlags.Default |
                               BindingFlags.GetProperty, null,
                               oDocCustomProps, new object[] { propertyName });

    Type typeDocAuthorProp = returned.GetType();
    returnVal = typeDocAuthorProp.InvokeMember("Value",
                               BindingFlags.Default |
                               BindingFlags.GetProperty,
                               null, returned,
                               new object[] { }).ToString();

    return returnVal;
}

0 个答案:

没有答案