Share via


DocumentBase.ProtectDocument 方法

讓您有機會在儲存快取資料之後將密碼保護重新套用至文件。

命名空間:  Microsoft.Office.Tools.Word
組件:  Microsoft.Office.Tools.Word.v4.0.Utilities (在 Microsoft.Office.Tools.Word.v4.0.Utilities.dll 中)

語法

'宣告
Protected Overridable Sub ProtectDocument
protected virtual void ProtectDocument()

備註

如果文件是透過使用密碼所保護,且包含可能在執行階段變更的快取資料,則在 Word 文件層級專案中覆寫這個方法。 在這個方法的實作中,請使用 Protect 方法來保護文件。

根據預設,當文件儲存時,不會保存受密碼保護之文件中的快取資料變更。 若要儲存快取資料的變更,您必須覆寫專案中的下列方法:

  • UnprotectDocument. 儲存文件時,Visual Studio Tools for Office Runtime 會呼叫這個方法。 為這個暫時取消保護文件的方法加入程式碼。 如此一來,就可以儲存快取資料的變更。

  • ProtectDocument. 儲存文件之後,Visual Studio Tools for Office Runtime 會呼叫這個方法。 為這個重新套用保護功能至文件的方法加入程式碼。

如需詳細資訊,請參閱如何:快取受密碼保護文件中的資料

即使快取資料因為發生某個與密碼保護無關的錯誤而無法儲存時,Visual Studio Tools for Office Runtime 仍會呼叫 ProtectDocument 方法。 例如,如果您實作 ICachedType 介面以自訂如何將快取資料儲存至文件,這時就會呼叫 ProtectDocument 方法,即使您的 ICachedType 實作擲回阻止儲存快取資料的例外狀況時也會呼叫。

範例

下列程式碼範例示範如何覆寫 ProtectDocument 方法,以重新套用因覆寫 UnprotectDocument 方法而移除的保護功能。 這段程式碼假設密碼儲存在名為 securelyStoredPassword 的欄位中。 若要使用這個範例,請在文件層級專案中的 ThisDocument 類別執行。

<CachedAttribute()> _
Public CachedString As String = "This string is cached in the document."

Private protectionTypeValue As Word.WdProtectionType

Protected Overrides Sub UnprotectDocument()
    If Me.ProtectionType <> Word.WdProtectionType.wdNoProtection Then
        protectionTypeValue = Me.ProtectionType
        Me.Unprotect(securelyStoredPassword)
    End If
End Sub

Protected Overrides Sub ProtectDocument()
    Me.Protect(protectionTypeValue, password:=securelyStoredPassword)
End Sub
[CachedAttribute]
public string CachedString = "This string is cached in the document.";

private Word.WdProtectionType protectionTypeValue;

protected override void UnprotectDocument()
{
    if (this.ProtectionType != Word.WdProtectionType.wdNoProtection)
    {
        protectionTypeValue = this.ProtectionType;
        this.Unprotect(ref securelyStoredPassword);
    }
}

protected override void ProtectDocument()
{
    this.Protect(protectionTypeValue, ref missing,
        ref securelyStoredPassword, ref missing, ref missing);
}

.NET Framework 安全性

請參閱

參考

DocumentBase 類別

Microsoft.Office.Tools.Word 命名空間

UnprotectDocument

其他資源

快取資料

如何:快取受密碼保護文件中的資料