Документы Word можно защитить различными способами, в зависимости от требований безопасности. Чтобы предотвратить открытие документа посторонними лицами, вы можете зашифруйте его паролем. Чтобы пользователи могли открывать документ, но не редактировать или изменять его содержимое, вы можете сделать документ доступным только для чтения или пометить его как окончательный. Чтобы разрешить пользователям изменять части документа, вы можете заблокировать весь документ, но оставить определенные разделы доступными для редактирования. В этой статье основное внимание уделяется тому, как защитить или снять защиту документа Word на C# и VB.NET с помощью Spire.Doc for .NET.

Установите Spire.Doc for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.Doc

Защита паролем документа Word в C#, VB.NET

Шифрование документа с помощью пароля гарантирует, что только вы и определенные люди смогут его читать или редактировать. Ниже приведены шаги по защите документа Word паролем с помощью Spire.Doc for .NET.

  • Создайте объект Документ.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Зашифруйте документ паролем, используя метод Document.Encrypt().
  • Сохраните документ в другой файл Word, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace PasswordProtectWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\test.docx");
    
                //Encrypt the document with a password
                document.Encrypt("open-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Encryption.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Изменение разрешения документа Word в C#, VB.NET

Документы, зашифрованные открытым паролем, не могут быть открыты теми, кто не знает пароля. Если вы хотите предоставить людям разрешение на чтение вашего документа, но ограничить типы изменений, которые кто-либо может внести, вы можете установить разрешение документа. Ниже приведены шаги по изменению разрешения документа Word с помощью Spire.Doc for .NET.

  • Создайте объект Документ.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Установите разрешение документа и установите пароль разрешения, используя метод Document.Protect().
  • Сохраните документ в другой файл Word, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ChangeDocumentPermission
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set the document permission and set the permission password
                document.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Permission.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Блокировка указанных разделов документа Word в C#, VB.NET

Защищая документ, вы можете заблокировать его части, чтобы их нельзя было изменить, а незаблокированные части оставить доступными для редактирования. Ниже приведены действия по защите определенных разделов документа Word с помощью Spire.Doc for .NET.

  • Создайте объект Документ.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Установите ограничение на редактирование как AllowOnlyFormFields.
  • Снимите защиту определенного раздела, установив для Document.Sections[index].ProtectForm значение false. Остальные разделы по-прежнему будут защищены.
  • Сохраните документ в другой файл Word, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ProtectSpecificSection
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set editing restriction as "AllowOnlyFormFields"
                doc.Protect(ProtectionType.AllowOnlyFormFields, "permissionPsd");
    
                //Unprotect section 2
                doc.Sections[1].ProtectForm = false;
    
                //Save the document to another Word file
                doc.SaveToFile("ProtectSection.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Пометить документ Word как окончательный в C#, VB.NET

Помечая документ как окончательный, вы отключаете возможности ввода, редактирования и изменения формата, и любому читателю появится сообщение о том, что документ завершен. Ниже приведены шаги, позволяющие пометить документ Word как окончательный с помощью Spire.Doc for .NET.

  • Создайте объект Документ.
  • Загрузите файл Word с помощью метода Document.LoadFromFile().
  • Получите объект CustomDocumentProperties из документа.
  • Добавьте в документ пользовательское свойство «_MarkAsFinal».
  • Сохраните документ в другой файл Word, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MarkAsFinal
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Get custom document properties
                CustomDocumentProperties customProperties = doc.CustomDocumentProperties;
    
                //Add "_MarkAsFinal" property to the document
                customProperties.Add("_MarkAsFinal", true);
    
                //Save the document to another Word file
                doc.SaveToFile("MarkAsFinal.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Удаление пароля из документа Word на C#, VB.NET

Вы можете удалить пароль из зашифрованного документа, если шифрование больше не требуется. Ниже приведены подробные шаги.

  • Создайте объект Документ.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Удалите пароль с помощью метода Document.RemoveEncryption().
  • Сохраните документ в другой файл Word, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace RemovePassword
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load an encrypted Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Encryption.docx", FileFormat.Docx, "open-psd");
    
                //Remove encryption
                document.RemoveEncryption();
    
                //Save the document to another Word file
                document.SaveToFile("Decryption.docx", FileFormat.Docx);
            }
        }
    }

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также

Je nach Sicherheitsanforderungen können Word-Dokumente auf unterschiedliche Weise geschützt werden. Um zu verhindern, dass Unbefugte ein Dokument öffnen, können Sie es mit einem Passwort verschlüsseln. Damit Benutzer das Dokument öffnen, seinen Inhalt jedoch nicht bearbeiten oder ändern können, können Sie das Dokument schreibgeschützt machen oder es als endgültig markieren. Damit Benutzer Teile des Dokuments ändern können, können Sie das gesamte Dokument sperren Lassen Sie bestimmte Abschnitte verfügbar zum Bearbeiten. Dieser Artikel konzentriert sich auf die Vorgehensweise Schützen Sie ein Word-Dokument in C# und VB.NET mit Spire.Doc for .NEToder heben Sie den Schutz auf.

Installieren Sie Spire.Doc for .NET

Zunächst müssen Sie die im Spire.Doc for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.Doc

Schützen Sie ein Word-Dokument mit einem Passwort in C#, VB.NET

Durch die Verschlüsselung eines Dokuments mit einem Passwort wird sichergestellt, dass nur Sie und bestimmte Personen es lesen oder bearbeiten können. Im Folgenden finden Sie die Schritte zum Schützen eines Word-Dokuments mit einem Kennwort mithilfe von Spire.Doc for .NET.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Verschlüsseln Sie das Dokument mit der Methode Document.Encrypt() mit einem Passwort.
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer anderen Word-Datei.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace PasswordProtectWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\test.docx");
    
                //Encrypt the document with a password
                document.Encrypt("open-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Encryption.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Ändern Sie die Berechtigung eines Word-Dokuments in C#, VB.NET

Mit einem offenen Passwort verschlüsselte Dokumente können von Personen, die das Passwort nicht kennen, nicht geöffnet werden. Wenn Sie Personen die Berechtigung erteilen möchten, Ihr Dokument zu lesen, aber die Art der Änderungen, die jemand vornehmen kann, einschränken möchten, können Sie die Dokumentberechtigung festlegen. Im Folgenden finden Sie die Schritte zum Ändern der Berechtigung eines Word-Dokuments mithilfe von Spire.Doc for .NET.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Legen Sie die Dokumentberechtigung und das Berechtigungskennwort mit der Methode Document.Protect() fest.
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer anderen Word-Datei.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ChangeDocumentPermission
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set the document permission and set the permission password
                document.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Permission.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Sperren Sie bestimmte Abschnitte eines Word-Dokuments in C#, VB.NET

Wenn Sie Ihr Dokument schützen, können Sie Teile davon sperren, sodass sie nicht geändert werden können, und die entsperrten Teile für die Bearbeitung verfügbar lassen. Im Folgenden finden Sie die Schritte zum Schutz bestimmter Abschnitte eines Word-Dokuments mit Spire.Doc for .NET.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Legen Sie die Bearbeitungsbeschränkung auf AllowOnlyFormFields fest.
  • Heben Sie den Schutz eines bestimmten Abschnitts auf, indem Sie Document.Sections[index].ProtectForm auf „false“ setzen. Die restlichen Abschnitte bleiben weiterhin geschützt.
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer anderen Word-Datei.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ProtectSpecificSection
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set editing restriction as "AllowOnlyFormFields"
                doc.Protect(ProtectionType.AllowOnlyFormFields, "permissionPsd");
    
                //Unprotect section 2
                doc.Sections[1].ProtectForm = false;
    
                //Save the document to another Word file
                doc.SaveToFile("ProtectSection.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Markieren Sie ein Word-Dokument in C#, VB.NET als endgültig

Indem Sie ein Dokument als „Endgültig“ markieren, deaktivieren Sie die Eingabe-, Bearbeitungs- und Formatänderungsfunktionen und jedem Leser wird eine Meldung angezeigt, dass das Dokument fertiggestellt wurde. Im Folgenden finden Sie die Schritte zum Markieren eines Word-Dokuments als endgültig mit Spire.Doc for .NET.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Word-Datei mit der Methode Document.LoadFromFile().
  • Rufen Sie das CustomDocumentProperties-Objekt aus dem Dokument ab.
  • Fügen Sie dem Dokument eine benutzerdefinierte Eigenschaft „_MarkAsFinal“ hinzu.
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer anderen Word-Datei.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MarkAsFinal
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Get custom document properties
                CustomDocumentProperties customProperties = doc.CustomDocumentProperties;
    
                //Add "_MarkAsFinal" property to the document
                customProperties.Add("_MarkAsFinal", true);
    
                //Save the document to another Word file
                doc.SaveToFile("MarkAsFinal.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Entfernen Sie das Passwort aus einem Word-Dokument in C#, VB.NET

Sie können das Passwort aus einem verschlüsselten Dokument entfernen, wenn die Verschlüsselung nicht mehr benötigt wird. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Entfernen Sie das Passwort mit der Methode Document.RemoveEncryption().
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer anderen Word-Datei.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace RemovePassword
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load an encrypted Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Encryption.docx", FileFormat.Docx, "open-psd");
    
                //Remove encryption
                document.RemoveEncryption();
    
                //Save the document to another Word file
                document.SaveToFile("Decryption.docx", FileFormat.Docx);
            }
        }
    }

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Los documentos de Word se pueden proteger de diversas formas, según los requisitos de seguridad. Para evitar que personas no autorizadas abran un documento, puede cifrarlo con una contraseña. Para permitir que los usuarios abran el documento, pero no editen ni modifiquen su contenido, puede hacer que el documento sea de solo lectura o marcarlo como final.. Para permitir que los usuarios modifiquen partes del documento, puede bloquear todo el documento pero dejar que secciones específicas estén disponibles para editar. Este artículo se centra en cómo proteger o desproteger un documento de Word en C# y VB.NET usando Spire.Doc for .NET.

Instalar Spire.Doc for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.Doc for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

PM> Install-Package Spire.Doc

Proteger con contraseña un documento de Word en C#, VB.NET

Cifrar un documento con una contraseña garantiza que solo usted y determinadas personas puedan leerlo o editarlo. Los siguientes son los pasos para proteger un documento de Word con una contraseña usando Spire.Doc for .NET.

  • Crea un objeto de documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Cifre el documento con una contraseña utilizando el método Document.Encrypt().
  • Guarde el documento en otro archivo de Word utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace PasswordProtectWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\test.docx");
    
                //Encrypt the document with a password
                document.Encrypt("open-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Encryption.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Cambiar permiso de un documento de Word en C#, VB.NET

Los documentos cifrados con una contraseña abierta no pueden ser abiertos por quienes no conocen la contraseña. Si desea otorgar permiso a las personas para leer su documento pero restringir los tipos de modificaciones que alguien puede realizar, puede configurar el permiso del documento. Los siguientes son los pasos para cambiar el permiso de un documento de Word usando Spire.Doc for .NET.

  • Crea un objeto de documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Establezca el permiso del documento y establezca la contraseña de permiso utilizando el método Document.Protect().
  • Guarde el documento en otro archivo de Word utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ChangeDocumentPermission
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set the document permission and set the permission password
                document.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Permission.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Bloquear secciones específicas de un documento de Word en C#, VB.NET

Cuando protege su documento, puede bloquear partes del mismo para que no se puedan cambiar y dejar las partes desbloqueadas disponibles para editar. Los siguientes son los pasos para proteger secciones específicas de un documento de Word usando Spire.Doc for .NET.

  • Crea un objeto de documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Establezca la restricción de edición como AllowOnlyFormFields.
  • Desproteja una sección específica configurando Document.Sections[index].ProtectForm en falso. El resto de tramos seguirán protegidos.
  • Guarde el documento en otro archivo de Word utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ProtectSpecificSection
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set editing restriction as "AllowOnlyFormFields"
                doc.Protect(ProtectionType.AllowOnlyFormFields, "permissionPsd");
    
                //Unprotect section 2
                doc.Sections[1].ProtectForm = false;
    
                //Save the document to another Word file
                doc.SaveToFile("ProtectSection.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Marcar un documento de Word como final en C#, VB.NET

Al marcar un documento como Final, deshabilita las capacidades de escritura, edición y cambios de formato y aparecerá un mensaje a cualquier lector indicando que el documento ha sido finalizado. Los siguientes son los pasos para marcar un documento de Word como final usando Spire.Doc for .NET.

  • Crea un objeto de documento.
  • Cargue un archivo de Word usando el método Document.LoadFromFile().
  • Obtenga el objeto CustomDocumentProperties del documento.
  • Agregue una propiedad personalizada "_MarkAsFinal" al documento.
  • Guarde el documento en otro archivo de Word utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MarkAsFinal
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Get custom document properties
                CustomDocumentProperties customProperties = doc.CustomDocumentProperties;
    
                //Add "_MarkAsFinal" property to the document
                customProperties.Add("_MarkAsFinal", true);
    
                //Save the document to another Word file
                doc.SaveToFile("MarkAsFinal.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Eliminar contraseña de un documento de Word en C#, VB.NET

Puede eliminar la contraseña de un documento cifrado si ya no es necesario el cifrado. Los siguientes son los pasos detallados.

  • Crea un objeto de documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Elimine la contraseña utilizando el método Document.RemoveEncryption().
  • Guarde el documento en otro archivo de Word utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace RemovePassword
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load an encrypted Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Encryption.docx", FileFormat.Docx, "open-psd");
    
                //Remove encryption
                document.RemoveEncryption();
    
                //Save the document to another Word file
                document.SaveToFile("Decryption.docx", FileFormat.Docx);
            }
        }
    }

Solicite una licencia temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también

Word 문서는 보안 요구 사항에 따라 다양한 방법으로 보호할 수 있습니다. 권한이 없는 사람이 문서를 열지 못하도록 하려면 다음을 수행하세요 비밀번호로 암호화하세요. 사용자가 문서를 열 수 있지만 내용을 편집하거나 수정할 수 없도록 하려면 다음을 수행합니다 문서를 읽기 전용으로 만들기 또는 최종으로 표시하세요. 사용자가 문서의 일부를 수정할 수 있도록 허용하려면 문서 전체를 잠그되 지정된 섹션을 사용할 수 있도록 허용 편집용. 이 기사에서는 다음 방법에 중점을 둡니다 C#VB.NET 에서 Word 문서 보호 또는 보호 해제 Spire.Doc for .NET을 사용합니다.

Spire.Doc for .NET 설치

먼저 Spire.Doc for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

PM> Install-Package Spire.Doc

C#, VB.NET에서 Word 문서를 암호로 보호

문서를 비밀번호로 암호화하면 귀하와 특정 사람들만이 문서를 읽거나 편집할 수 있습니다. 다음은 Spire.Doc for .NET을 사용하여 Word 문서를 비밀번호로 보호하는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.Encrypt() 메서드를 사용하여 비밀번호로 문서를 암호화합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace PasswordProtectWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\test.docx");
    
                //Encrypt the document with a password
                document.Encrypt("open-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Encryption.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

C#, VB.NET에서 Word 문서의 권한 변경

공개 비밀번호로 암호화된 문서는 비밀번호를 모르는 사람은 열 수 없습니다. 사람들에게 문서를 읽을 수 있는 권한을 부여하고 수정 가능한 유형을 제한하려는 경우 문서 권한을 설정할 수 있습니다. 다음은 Spire.Doc for .NET을 사용하여 Word 문서의 권한을 변경하는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.Protect() 메서드를 사용하여 문서 권한을 설정하고 권한 비밀번호를 설정합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ChangeDocumentPermission
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set the document permission and set the permission password
                document.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Permission.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

C#, VB.NET에서 Word 문서의 지정된 섹션 잠금

문서를 보호할 때 문서의 일부를 변경할 수 없도록 잠그고 잠금 해제된 부분은 편집할 수 있도록 남겨둘 수 있습니다. 다음은 Spire.Doc for .NET을 사용하여 Word 문서의 특정 섹션을 보호하는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • 편집 제한을 AllowOnlyFormFields로 설정합니다.
  • Document.Sections[index].ProtectForm을 false로 설정하여 특정 섹션의 보호를 해제합니다. 나머지 섹션은 계속해서 보호됩니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ProtectSpecificSection
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set editing restriction as "AllowOnlyFormFields"
                doc.Protect(ProtectionType.AllowOnlyFormFields, "permissionPsd");
    
                //Unprotect section 2
                doc.Sections[1].ProtectForm = false;
    
                //Save the document to another Word file
                doc.SaveToFile("ProtectSection.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

C#, VB.NET에서 Word 문서를 최종 문서로 표시

문서를 최종본으로 표시하면 입력, 편집, 형식 변경 기능이 비활성화되고 모든 독자에게 문서가 완성되었다는 메시지가 표시됩니다. 다음은 Spire.Doc for .NET을 사용하여 Word 문서를 최종 문서로 표시하는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 파일을 로드합니다.
  • 문서에서 CustomDocumentProperties 개체를 가져옵니다.
  • 문서에 사용자 정의 속성 "_MarkAsFinal"을 추가합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MarkAsFinal
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Get custom document properties
                CustomDocumentProperties customProperties = doc.CustomDocumentProperties;
    
                //Add "_MarkAsFinal" property to the document
                customProperties.Add("_MarkAsFinal", true);
    
                //Save the document to another Word file
                doc.SaveToFile("MarkAsFinal.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

C#, VB.NET의 Word 문서에서 비밀번호 제거

암호화가 더 이상 필요하지 않은 경우 암호화된 문서에서 비밀번호를 제거할 수 있습니다. 자세한 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.RemoveEncryption() 메서드를 사용하여 비밀번호를 제거합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace RemovePassword
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load an encrypted Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Encryption.docx", FileFormat.Docx, "open-psd");
    
                //Remove encryption
                document.RemoveEncryption();
    
                //Save the document to another Word file
                document.SaveToFile("Decryption.docx", FileFormat.Docx);
            }
        }
    }

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

I documenti Word possono essere protetti in vari modi, a seconda dei requisiti di sicurezza. Per impedire a persone non autorizzate di aprire un documento, puoi crittografarlo con una password. Per consentire agli utenti di aprire il documento, ma non di modificarne il contenuto, puoi rendere il documento di sola lettura o contrassegnarlo come finale. Per consentire agli utenti di modificare parti del documento, puoi bloccare l'intero documento ma lasciare disponibili le sezioni specificate per la modifica. Questo articolo si concentra su come proteggere o rimuovere la protezione di un documento Word in C# e VB.NET utilizzando Spire.Doc for .NET.

Installa Spire.Doc for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.Doc for.NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.Doc

Proteggi con password un documento Word in C#, VB.NET

La crittografia di un documento con una password garantisce che solo tu e determinate persone possiate leggerlo o modificarlo. Di seguito sono riportati i passaggi per proteggere un documento Word con una password utilizzando Spire.Doc for .NET.

  • Creare un oggetto Documento.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Crittografa il documento con una password utilizzando il metodo Document.Encrypt().
  • Salva il documento in un altro file Word utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace PasswordProtectWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\test.docx");
    
                //Encrypt the document with a password
                document.Encrypt("open-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Encryption.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Modifica autorizzazione di un documento Word in C#, VB.NET

I documenti crittografati con una password aperta non possono essere aperti da chi non conosce la password. Se desideri concedere alle persone l'autorizzazione a leggere il tuo documento ma limitare i tipi di modifiche che qualcuno può apportare, puoi impostare l'autorizzazione del documento. Di seguito sono riportati i passaggi per modificare l'autorizzazione di un documento Word utilizzando Spire.Doc for .NET.

  • Creare un oggetto Documento.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Imposta l'autorizzazione del documento e imposta la password dell'autorizzazione utilizzando il metodo Document.Protect().
  • Salva il documento in un altro file Word utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ChangeDocumentPermission
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set the document permission and set the permission password
                document.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Permission.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Blocca sezioni specificate di un documento Word in C#, VB.NET

Quando proteggi il tuo documento, puoi bloccarne alcune parti in modo che non possano essere modificate e lasciare le parti sbloccate disponibili per la modifica. Di seguito sono riportati i passaggi per proteggere sezioni specifiche di un documento Word utilizzando Spire.Doc for .NET.

  • Creare un oggetto Documento.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Imposta la restrizione di modifica su EnableOnlyFormFields.
  • Rimuovere la protezione di una sezione specifica impostando Document.Sections[index].ProtectForm su false. Le restanti sezioni continueranno ad essere protette.
  • Salva il documento in un altro file Word utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ProtectSpecificSection
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set editing restriction as "AllowOnlyFormFields"
                doc.Protect(ProtectionType.AllowOnlyFormFields, "permissionPsd");
    
                //Unprotect section 2
                doc.Sections[1].ProtectForm = false;
    
                //Save the document to another Word file
                doc.SaveToFile("ProtectSection.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Contrassegna un documento Word come finale in C#, VB.NET

Contrassegnando un documento come Finale, disabiliti le funzionalità di digitazione, modifica e modifica del formato e a qualsiasi lettore verrà visualizzato un messaggio che informa che il documento è stato finalizzato. Di seguito sono riportati i passaggi per contrassegnare un documento Word come finale utilizzando Spire.Doc for .NET.

  • Creare un oggetto Documento.
  • Carica un file Word utilizzando il metodo Document.LoadFromFile().
  • Ottieni l'oggetto CustomDocumentProperties dal documento.
  • Aggiungi una proprietà personalizzata "_MarkAsFinal" al documento.
  • Salva il documento in un altro file Word utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MarkAsFinal
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Get custom document properties
                CustomDocumentProperties customProperties = doc.CustomDocumentProperties;
    
                //Add "_MarkAsFinal" property to the document
                customProperties.Add("_MarkAsFinal", true);
    
                //Save the document to another Word file
                doc.SaveToFile("MarkAsFinal.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Rimuovi la password da un documento Word in C#, VB.NET

È possibile rimuovere la password da un documento crittografato se la crittografia non è più necessaria. Di seguito sono riportati i passaggi dettagliati.

  • Creare un oggetto Documento.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Rimuovere la password utilizzando il metodo Document.RemoveEncryption().
  • Salva il documento in un altro file Word utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace RemovePassword
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load an encrypted Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Encryption.docx", FileFormat.Docx, "open-psd");
    
                //Remove encryption
                document.RemoveEncryption();
    
                //Save the document to another Word file
                document.SaveToFile("Decryption.docx", FileFormat.Docx);
            }
        }
    }

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Les documents Word peuvent être protégés de différentes manières, en fonction des exigences de sécurité. Pour empêcher des personnes non autorisées d'ouvrir un document, vous pouvez le crypter avec un mot de passe. Pour permettre aux utilisateurs d'ouvrir le document, mais pas de modifier son contenu, vous pouvez rendre le document en lecture seule ou le marquer comme final.. Pour permettre aux utilisateurs de modifier des parties du document, vous pouvez verrouiller l'intégralité du document mais laisser les sections spécifiées disponibles pour l'édition. Cet article se concentre sur la façon de protéger ou déprotéger un document Word en C# et VB.NET à l'aide de Spire.Doc for .NET.

Installer Spire.Doc for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc for.NET comme références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.Doc

Protéger par mot de passe un document Word en C#, VB.NET

Le cryptage d'un document avec un mot de passe garantit que seuls vous et certaines personnes pouvez le lire ou le modifier. Voici les étapes pour protéger un document Word avec un mot de passe à l'aide de Spire.Doc for .NET.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Cryptez le document avec un mot de passe à l'aide de la méthode Document.Encrypt().
  • Enregistrez le document dans un autre fichier Word à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace PasswordProtectWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\test.docx");
    
                //Encrypt the document with a password
                document.Encrypt("open-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Encryption.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Modifier l'autorisation d'un document Word en C#, VB.NET

Les documents cryptés avec un mot de passe ouvert ne peuvent pas être ouverts par ceux qui ne connaissent pas le mot de passe. Si vous souhaitez autoriser les utilisateurs à lire votre document tout en limitant les types de modifications que quelqu'un peut apporter, vous pouvez définir l'autorisation du document. Voici les étapes pour modifier l'autorisation d'un document Word à l'aide de Spire.Doc for .NET.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Définissez l'autorisation du document et définissez le mot de passe d'autorisation à l'aide de la méthode Document.Protect().
  • Enregistrez le document dans un autre fichier Word à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ChangeDocumentPermission
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set the document permission and set the permission password
                document.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd");
    
                //Save the document to another Word file
                document.SaveToFile("Permission.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Verrouiller les sections spécifiées d'un document Word en C#, VB.NET

Lorsque vous protégez votre document, vous pouvez en verrouiller certaines parties afin qu'elles ne puissent pas être modifiées et laisser les parties déverrouillées disponibles pour l'édition. Voici les étapes pour protéger les sections spécifiées d'un document Word à l'aide de Spire.Doc for .NET.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Définissez la restriction de modification sur AllowOnlyFormFields.
  • Déprotégez une section spécifique en définissant Document.Sections[index].ProtectForm sur false. Les sections de repos continueront d'être protégées.
  • Enregistrez le document dans un autre fichier Word à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ProtectSpecificSection
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Set editing restriction as "AllowOnlyFormFields"
                doc.Protect(ProtectionType.AllowOnlyFormFields, "permissionPsd");
    
                //Unprotect section 2
                doc.Sections[1].ProtectForm = false;
    
                //Save the document to another Word file
                doc.SaveToFile("ProtectSection.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Marquer un document Word comme final en C#, VB.NET

En marquant un document comme Final, vous désactivez les capacités de saisie, d'édition et de modification de format et un message apparaîtra à tout lecteur indiquant que le document a été finalisé. Voici les étapes pour marquer un document Word comme final à l'aide de Spire.Doc for .NET.

  • Créez un objet Document.
  • Chargez un fichier Word à l'aide de la méthode Document.LoadFromFile().
  • Récupérez l'objet CustomDocumentProperties du document.
  • Ajoutez une propriété personnalisée "_MarkAsFinal" au document.
  • Enregistrez le document dans un autre fichier Word à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MarkAsFinal
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Get custom document properties
                CustomDocumentProperties customProperties = doc.CustomDocumentProperties;
    
                //Add "_MarkAsFinal" property to the document
                customProperties.Add("_MarkAsFinal", true);
    
                //Save the document to another Word file
                doc.SaveToFile("MarkAsFinal.docx");
            }
        }
    }

C#/VB.NET - How to Protect or Unprotect a Word Document

Supprimer le mot de passe d'un document Word en C#, VB.NET

Vous pouvez supprimer le mot de passe d'un document crypté si le cryptage n'est plus nécessaire. Voici les étapes détaillées.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Supprimez le mot de passe à l’aide de la méthode Document.RemoveEncryption().
  • Enregistrez le document dans un autre fichier Word à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace RemovePassword
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load an encrypted Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Encryption.docx", FileFormat.Docx, "open-psd");
    
                //Remove encryption
                document.RemoveEncryption();
    
                //Save the document to another Word file
                document.SaveToFile("Decryption.docx", FileFormat.Docx);
            }
        }
    }

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Installed via NuGet

PM> Install-Package Spire.Doc

Related Links

Document properties (also known as metadata) are a set of information about a document. All Word documents come with a set of built-in document properties, including title, author name, subject, keywords, etc. In addition to the built-in document properties, Microsoft Word also allows users to add custom document properties to Word documents. In this article, we will explain how to add these document properties to Word documents in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Add Built-in Document Properties to a Word Document in C# and VB.NET

A built-in document property consists of a name and a value. You cannot set or change the name of a built-in document property as it's predefined by Microsoft Word, but you can set or change its value. The following steps demonstrate how to set values for built-in document properties in a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the built-in document properties of the document through Document.BuiltinDocumentProperties property.
  • Set values for specific document properties such as title, subject and author through Title, Subject and Author properties of BuiltinDocumentProperties class.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace BuiltinDocumentProperties
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Add built-in document properties to the document
                BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
                standardProperties.Title = "Add Document Properties";
                standardProperties.Subject = "C# Example";
                standardProperties.Author = "James";
                standardProperties.Company = "Eiceblue";
                standardProperties.Manager = "Michael";
                standardProperties.Category = "Document Manipulation";
                standardProperties.Keywords = "C#, Word, Document Properties";
                standardProperties.Comments = "This article shows how to add document properties";
    
                //Save the result document
                document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Add Document Properties to Word Documents

Add Custom Document Properties to a Word Document in C# and VB.NET

A custom document property can be defined by a document author or user. Each custom document property should contain a name, a value and a data type. The data type can be one of these four types: Text, Date, Number and Yes or No. The following steps demonstrate how to add custom document properties with different data types to a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the custom document properties of the document through Document.CustomDocumentProperties property.
  • Add custom document properties with different data types to the document using CustomDocumentProperties.Add(string, object) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
    using System;
    
    namespace CustomDocumentProperties
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Add custom document properties to the document
                CustomDocumentProperties customProperties = document.CustomDocumentProperties;
                customProperties.Add("Document ID", 1);
                customProperties.Add("Authorized", true);
                customProperties.Add("Authorized By", "John Smith");
                customProperties.Add("Authorized Date", DateTime.Today);
    
                //Save the result document
                document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Add Document Properties to Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

As propriedades do documento (também conhecidas como metadados) são um conjunto de informações sobre um documento. Todos os documentos do Word vêm com um conjunto de propriedades de documento integradas, incluindo título, nome do autor, assunto, palavras-chave, etc. Além das propriedades de documento integradas, o Microsoft Word também permite que os usuários adicionem propriedades de documento personalizadas a documentos do Word. Neste artigo, explicaremos como adicione essas propriedades de documento a documentos do Word em C# e VB.NET usando Spire.Doc for .NET.

Instale o Spire.Doc for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.Doc

Adicionar propriedades de documento integradas a um documento do Word em C# e VB.NET

Uma propriedade de documento integrada consiste em um nome e um valor. Você não pode definir ou alterar o nome de uma propriedade interna do documento, pois ela é predefinida pelo Microsoft Word, mas pode definir ou alterar seu valor. As etapas a seguir demonstram como definir valores para propriedades internas do documento em um documento do Word:

  • Inicialize uma instância da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha as propriedades internas do documento por meio da propriedade Document.BuiltinDocumentProperties.
  • Defina valores para propriedades específicas do documento, como título, assunto e autor, por meio das propriedades Título, Assunto e Autor da classe BuiltinDocumentProperties.
  • Salve o documento resultante usando o método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace BuiltinDocumentProperties
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Add built-in document properties to the document
                BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
                standardProperties.Title = "Add Document Properties";
                standardProperties.Subject = "C# Example";
                standardProperties.Author = "James";
                standardProperties.Company = "Eiceblue";
                standardProperties.Manager = "Michael";
                standardProperties.Category = "Document Manipulation";
                standardProperties.Keywords = "C#, Word, Document Properties";
                standardProperties.Comments = "This article shows how to add document properties";
    
                //Save the result document
                document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Add Document Properties to Word Documents

Adicionar propriedades de documento personalizadas a um documento do Word em C# e VB.NET

Uma propriedade de documento personalizada pode ser definida por um autor ou usuário do documento. Cada propriedade personalizada do documento deve conter um nome, um valor e um tipo de dados. O tipo de dados pode ser um destes quatro tipos: Texto, Data, Número e Sim ou Não. As etapas a seguir demonstram como adicionar propriedades de documento personalizadas com diferentes tipos de dados a um documento do Word:

  • Inicialize uma instância da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha as propriedades personalizadas do documento por meio da propriedade Document.CustomDocumentProperties.
  • Adicione propriedades de documento personalizadas com diferentes tipos de dados ao documento usando o método CustomDocumentProperties.Add(string, object).
  • Salve o documento resultante usando o método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using System;
    
    namespace CustomDocumentProperties
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Add custom document properties to the document
                CustomDocumentProperties customProperties = document.CustomDocumentProperties;
                customProperties.Add("Document ID", 1);
                customProperties.Add("Authorized", true);
                customProperties.Add("Authorized By", "John Smith");
                customProperties.Add("Authorized Date", DateTime.Today);
    
                //Save the result document
                document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Add Document Properties to Word Documents

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Свойства документа (также известные как метаданные) — это набор информации о документе. Все документы Word имеют набор встроенных свойств документа, включая заголовок, имя автора, тему, ключевые слова и т. д. В дополнение к встроенным свойствам документа Microsoft Word также позволяет пользователям добавлять собственные свойства документа в документы Word. В этой статье мы объясним, как добавить эти свойства документа в документы Word на C# и VB.NET использование Spire.Doc for .NET.

Установите Spire.Doc for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.Doc

Добавление встроенных свойств документа в документ Word на C# и VB.NET

Встроенное свойство документа состоит из имени и значения. Вы не можете установить или изменить имя встроенного свойства документа, поскольку оно предопределено в Microsoft Word, но вы можете установить или изменить его значение. Следующие шаги демонстрируют, как установить значения для встроенных свойств документа в документе Word:

  • Инициализируйте экземпляр класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получите встроенные свойства документа через свойство Document.BuiltinDocumentProperties.
  • Установите значения для конкретных свойств документа, таких как заголовок, тема и автор, с помощью свойств Title, Тема и Автор класса InternalDocumentProperties.
  • Сохраните полученный документ с помощью метода Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace BuiltinDocumentProperties
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Add built-in document properties to the document
                BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
                standardProperties.Title = "Add Document Properties";
                standardProperties.Subject = "C# Example";
                standardProperties.Author = "James";
                standardProperties.Company = "Eiceblue";
                standardProperties.Manager = "Michael";
                standardProperties.Category = "Document Manipulation";
                standardProperties.Keywords = "C#, Word, Document Properties";
                standardProperties.Comments = "This article shows how to add document properties";
    
                //Save the result document
                document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Add Document Properties to Word Documents

Добавление пользовательских свойств документа в документ Word на C# и VB.NET

Пользовательское свойство документа может быть определено автором или пользователем документа. Каждое свойство настраиваемого документа должно содержать имя, значение и тип данных. Тип данных может быть одним из этих четырех типов: «Текст», «Дата», «Число» и «Да» или «Нет». Следующие шаги демонстрируют, как добавить в документ Word пользовательские свойства документа с различными типами данных:

  • Инициализируйте экземпляр класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получите пользовательские свойства документа через свойство Document.CustomDocumentProperties.
  • Добавьте в документ пользовательские свойства документа с разными типами данных с помощью метода CustomDocumentProperties.Add(string, object).
  • Сохраните полученный документ с помощью метода Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using System;
    
    namespace CustomDocumentProperties
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Add custom document properties to the document
                CustomDocumentProperties customProperties = document.CustomDocumentProperties;
                customProperties.Add("Document ID", 1);
                customProperties.Add("Authorized", true);
                customProperties.Add("Authorized By", "John Smith");
                customProperties.Add("Authorized Date", DateTime.Today);
    
                //Save the result document
                document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Add Document Properties to Word Documents

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также

Dokumenteigenschaften (auch Metadaten genannt) sind eine Reihe von Informationen über ein Dokument. Alle Word-Dokumente verfügen über eine Reihe integrierter Dokumenteigenschaften, darunter Titel, Name des Autors, Betreff, Schlüsselwörter usw. Zusätzlich zu den integrierten Dokumenteigenschaften ermöglicht Microsoft Word Benutzern auch das Hinzufügen benutzerdefinierter Dokumenteigenschaften zu Word-Dokumenten. In diesem Artikel erklären wir, wie Sie diese Dokumenteigenschaften zu Word-Dokumenten in C# und VB.NET hinzufügen Verwendung von Spire.Doc for .NET.

Installieren Sie Spire.Doc for .NET

Zunächst müssen Sie die im Spire.Doc for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.Doc

Fügen Sie integrierte Dokumenteigenschaften zu einem Word-Dokument in C# und VB.NET hinzu

Eine integrierte Dokumenteigenschaft besteht aus einem Namen und einem Wert. Sie können den Namen einer integrierten Dokumenteigenschaft nicht festlegen oder ändern, da er von Microsoft Word vordefiniert ist, Sie können jedoch ihren Wert festlegen oder ändern. Die folgenden Schritte veranschaulichen, wie Werte für integrierte Dokumenteigenschaften in einem Word-Dokument festgelegt werden:

  • Initialisieren Sie eine Instanz der Document-Klasse.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie die integrierten Dokumenteigenschaften des Dokuments über die Eigenschaft Document.BuiltinDocumentProperties ab.
  • Legen Sie Werte für bestimmte Dokumenteigenschaften wie Titel, Betreff und Autor über die Eigenschaften „Titel“, „Betreff“ und „Autor“ der Klasse „BuiltinDocumentProperties“ fest.
  • Speichern Sie das Ergebnisdokument mit der Methode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace BuiltinDocumentProperties
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Add built-in document properties to the document
                BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
                standardProperties.Title = "Add Document Properties";
                standardProperties.Subject = "C# Example";
                standardProperties.Author = "James";
                standardProperties.Company = "Eiceblue";
                standardProperties.Manager = "Michael";
                standardProperties.Category = "Document Manipulation";
                standardProperties.Keywords = "C#, Word, Document Properties";
                standardProperties.Comments = "This article shows how to add document properties";
    
                //Save the result document
                document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Add Document Properties to Word Documents

Fügen Sie benutzerdefinierte Dokumenteigenschaften zu einem Word-Dokument in C# und VB.NET hinzu

Eine benutzerdefinierte Dokumenteigenschaft kann von einem Dokumentautor oder -benutzer definiert werden. Jede benutzerdefinierte Dokumenteigenschaft sollte einen Namen, einen Wert und einen Datentyp enthalten. Der Datentyp kann einer dieser vier Typen sein: Text, Datum, Zahl und Ja oder Nein. Die folgenden Schritte zeigen, wie Sie einem Word-Dokument benutzerdefinierte Dokumenteigenschaften mit unterschiedlichen Datentypen hinzufügen:

  • Initialisieren Sie eine Instanz der Document-Klasse.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie die benutzerdefinierten Dokumenteigenschaften des Dokuments über die Eigenschaft Document.CustomDocumentProperties ab.
  • Fügen Sie dem Dokument benutzerdefinierte Dokumenteigenschaften mit unterschiedlichen Datentypen hinzu, indem Sie die Methode CustomDocumentProperties.Add(string, object) verwenden.
  • Speichern Sie das Ergebnisdokument mit der Methode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using System;
    
    namespace CustomDocumentProperties
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Add custom document properties to the document
                CustomDocumentProperties customProperties = document.CustomDocumentProperties;
                customProperties.Add("Document ID", 1);
                customProperties.Add("Authorized", true);
                customProperties.Add("Authorized By", "John Smith");
                customProperties.Add("Authorized Date", DateTime.Today);
    
                //Save the result document
                document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Add Document Properties to Word Documents

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch