Как записать параметры защиты в документе DOCX на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите/создайте документ DOCX.
  3. Укажите пароль в свойстве Write Protection от записи.
  4. Сохраните документ как DOCX.

    Документ Word (файл .docx) с защитой от записи открывается в приложениях Word в режиме только для чтения. Содержимое документа можно редактировать, но его нельзя повторно сохранить с тем же именем файла.

В этом примере кода мы создаем документ и сохраняем его с помощью write protection options.

Полный код

using System;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;
using System.IO;
using System.Linq;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            WriteProtection();
        }

        /// <summary>
        /// Create a write protected DOCX document.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/write-protection-options-net-csharp-vb.php
        /// </remarks>
        public static void WriteProtection()
        {
            string filePath = @"ProtectedDocument.docx";

            DocumentCore dc = new DocumentCore();

            // Insert paragraphs into the document.
            dc.Sections.Add(
           new Section(dc,
               new Paragraph(dc, "This document has been opened in read only mode."),
               new Paragraph(dc, "To keep your changes, you 'll need to save the document with a new name or in a different location."),
               new Paragraph(dc, "To make changes to the current document, restart with the password '12345'.")));

            // Sets the write protection password "12345".
            DocumentWriteProtection protection = dc.WriteProtection;
            protection.SetPassword("12345");

            // Save a document as the DOCX file with write protection options.
            dc.Save(filePath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing
Imports System.IO
Imports System.Linq

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			WriteProtection()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' Create a write protected DOCX document.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/write-protection-options-net-csharp-vb.php
		''' </remarks>
		Public Shared Sub WriteProtection()
			Dim filePath As String = "ProtectedDocument.docx"

			Dim dc As New DocumentCore()

			' Insert paragraphs into the document.
			dc.Sections.Add(New Section(dc, New Paragraph(dc, "This document has been opened in read only mode."),
										New Paragraph(dc, "To keep your changes, you 'll need to save the document with a new name or in a different location."),
										New Paragraph(dc, "To make changes to the current document, restart with the password '12345'.")))

			' Sets the write protection password "12345".
			Dim protection As DocumentWriteProtection = dc.WriteProtection
			protection.SetPassword("12345")

			' Save a document as the DOCX file with write protection options.
			dc.Save(filePath)

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.