Click here to Skip to main content
14,126,835 members
Click here to Skip to main content
Add your own
alternative version

Stats

18.8K views
933 downloads
15 bookmarked
Posted 24 Nov 2015
Licenced CPOL

Protect word document using C# and Word Automation

, 24 Nov 2015
Rate this:
Please Sign up or sign in to vote.
This article explain you How to protect word document using C# and Word automation

Are you looking for a way to protect your word document programmatically ? Are you looking for a way to give 'readonly' access to your word file so that no one should edit it ? Are you looking for a way to secure your word file in a such way that it can be only used for 'view purpose', and no one should copy contents of it ? Are looking for a way to secure your word file in a such a way that the changes done by another person get tracked/audited?

If yes, then you are at right place, we can secure our word file programmatically and cover all above scenarios, this article will give you answer of all your word securities question

 

Background

Most of the time we use Microsoft word for our documentation purpose and we prefer, it should be secure enough, but can we really know how to make word file secure ? Many of us is unaware of it, Do we know how many types of securities we can add to word file ? if Not, Don't worry this article will let you travel through the security world

Let's start

How to protect word file?

1. File level protection

1. Document ask password to open a file (Open file security), without password file will not open

2. Document ask password to edit file  (Modify file security), if we do not have a password to modify still we can open file in Readonly mode

Note: If you lose or forget the password it is not easily recoverable.

2. Content level protection

With this type of protection we can deal with file content security, there are 5 types of protection, see below

1. ReadOnly

2. Track changes

3. Comments only

4. Filling in forms

5. Partial locking

Let's discuss them in detail

1. ReadOnly Protection

If we protect document with ReadOnly protection then document gets locked and all editing options are get disabled.  To apply this security you need to go to Developer Tab - Select Protect document - select restrict formatting and editing - select Only this type of editing in the document checkbox - select Nochanges(ReadOnly) option from dropdown then click on Yes, Start enforcing protection button, see below snap

Can't find Developer Tab ??? follow the image below

Make Read-Only protection enable

2. Comments-Only Protection

If we protect document with CommentsOnly protection then document gets locked and all editing options are get disabled, just the difference is, we can only put comments in document. Once document gets locked with comments only locking, each user comments recorded with different color for identification. You can follow above same steps to lock document, just select 'Comments' from dropdown, see below snap to check how behave document with comments, see below snap

3. Tracked changes

Once document is locked with 'TrackedChanges' it can be editable but all activities/changes done by user are get tracked, the changes are painted with different color than original document font color, which easily identified the changes. see below snap

4. Filling in forms

Once document is locked with 'filling in forms' option, we can only fill text in forms fields, all other editing options are disabled, see below snap

5. Partial locking/ lock in parts

Partial locking can be done in Word file, there is no direct option to lock partial file or files in parts, we can achieve by using following steps

- Click on protect document - select Restrict formatting and editing - select No changes (Read Only) in editing restrictions - Select part of the document you want to keep free to edit - click Everyone checkbox in Exceptions and finally click on 'Yes, start enforcing protection' button, see below snap

Travel with the code

We have seen all protection types in word, we have locked them manually now its time to do it programmatically

Things we need 

Before start cooking we need Visual studio, C# and Word (2007+)

Getting started

First step is to create a New solution in C# with visual studio and add reference of interop assemblies in our code, version of interop libraries are depend upon version of Microsoft, see below table

MS-Word installed Interop Version
2003 8.0 Word Object library
2007 12.0 Word Object library
2010 14.0 Word Object library
2013 15.0 Word Object library

If you are beginner to Word Interop automation with C# then you should go with this article Word Automation with C#, After adding interop reference we need to create Application object and Document object, see below snippet

Word._Application objApp = null;
Word._Document objDoc = null;

After creating Application and Document object, we can open any document and accesss them easily, see below snippet one by one

1. Open file security (Password to open a file)

//Create application object and open existing document
objApp = new Word.Application();
objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);

if (objDoc.ProtectionType == Word.WdProtectionType.wdNoProtection) //check if the document is alreay protected
{
    objDoc.Password = szPassword.ToString(); //set password to open file
    objDoc.ReadOnlyRecommended = false;
    objDoc.Save(); //save word document
    MessageBox.Show("Word locked for OpenFile successfully !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    MessageBox.Show("Word document is already protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

In above snippet, We have use ProtectionType property of document object to check if the document is already protected, and Password helps us to set password to open word document.

2. Modify file security (Password to modify a file)

//Create application object and open existing document
objApp = new Word.Application();
objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);

if (objDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
{
    objDoc.Password = "";
    objDoc.WritePassword = szPassword.ToString(); //use WritePassword attribute to set password for modify file
    objDoc.ReadOnlyRecommended = false;
    objDoc.Save();
    MessageBox.Show("Word locked for Modify File scurity successfully !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    MessageBox.Show("Word document is already protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

In above snippet, We have use WritePassword propety to set password for modify file, Save() method is used to save document.

3. ReadOnly Protection

//Create application object and open existing document
objApp = new Word.Application();
objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);

if (objDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
{
    objDoc.Protect(Word.WdProtectionType.wdAllowOnlyReading, ref bFalse, ref szPassword, ref bFalse, ref bTrue); //use protect method to protect your word file
    objDoc.Save();
    MessageBox.Show("Word document Protected successfully (for Read only)!", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    MessageBox.Show("Word document is already protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

In above snippet, We have use Protect method to lock document, Protect method work according to the parameters we have used, here we have pass 'wdAllowOnlyReading' enum to protect file as ReadOnly.

4. Comments-Only Protection

//Create application object and open existing document
objApp = new Word.Application();
objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);

if (objDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
{
    objDoc.Protect(Word.WdProtectionType.wdAllowOnlyComments, ref bFalse, ref szPassword, ref bFalse, ref bTrue); //here we use 'wdAllowOnlyComments' as protection type to locked word document
    objDoc.Save();
    MessageBox.Show("Word document Protected successfully (for Comments only)!", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    MessageBox.Show("Word document is already protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

In above snippet, we have use 'wdAllowCommentsOnly' as protection type to locked word document for comments only.

4. Tracked changes

//Create application object and open existing document
objApp = new Word.Application();
objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);

if (objDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
{
    objDoc.Protect(Word.WdProtectionType.wdAllowOnlyRevisions, ref bFalse, ref szPassword, ref bFalse, ref bTrue); //wdAllowOnlyRevisions used for Tracked changes locking
    objDoc.Save();
    MessageBox.Show("Word document Protected successfully (for TrackChanges only)!", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    MessageBox.Show("Word document is already protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

In above snippet, we have use 'wdAllowOnlyRevisions' as protection type to locked word document for tracked changes only.

5. Filling in forms

//Create application object and open existing document
objApp = new Word.Application();
objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);

if (objDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
{
    objDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, ref bFalse, ref szPassword, ref bFalse, ref bTrue); //use protect method to protect your word file
    objDoc.Save();
    MessageBox.Show("Word document Protected successfully (for Read only)!", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    MessageBox.Show("Word document is already protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

In above snippet, we have use 'wdAllowOnlyFormsFields' as protection type to locked word document for form fields locking only.

Unlocking word document

//Create application object and open existing document
objApp = new Word.Application();
objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,
    ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);

if (objDoc.ProtectionType != Word.WdProtectionType.wdNoProtection)
{
    objDoc.Unprotect(ref szPassword);
    objDoc.Save();
    MessageBox.Show("Word document UnProtected successfully !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
    MessageBox.Show("Selected word document is not protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Error);

In above snippet we have use 'UnProtect()' method to unprotect word document

Finally...

COM/Interop objects are very heavy and unmanaged objects, GC alone can not able to collect them and dispose them, we SHOULD release objects after we have use them, finally is the recommended place to release all com objects, Close() and quit() methods are used to release Document and Application object respectively. see below snippet

finally
{
    //Winword is heavy and unmanaged object, you should release all resources used for it
    if (objDoc != null)
    {
        objDoc.Close();
        objDoc = null;
    }
    if (objApp != null)
    {
        objApp.Quit();
        objApp = null;
    }
}
Application Scenarios

- If you want your word document should ask password to open file, you can use Password to open a file security

- If you want to open file only for reading purpose only you can use Modify file security or ReadOnly protection

- If you want peoples to edit your file but needs to audit that changes then you can use Tracked changes security

- If you want peoples, not to copy/paste your word file content and not to edit it then you can locked word document with Forms filing security

- If you have fillable forms and you want peoples to edit only in forms fields then you can locked word document with Forms filing security

- If you want peoples to edit only some part of your document then you can use partial locking security

Programming with word application is a epic, it will not finished in couple of articles, i will cover more points in upcoming versions of this article, till then you can enjoy this stuff

Article scope : MS-Word 2007/2010/2013+, Visual studio 2005+

Suggestion and Queries are always welcome

Thanks

koolprasad2003

License

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

Share

About the Author

koolprasadd
Software Developer (Senior)
India India
Hi there, I am Prasad. Author, Blogger, contributor and passionate about Microsoft .NET technologies. I like to write an articles/blogs on different .NET aspects and like to help Developers, to resolve their issues and boost them on Microsoft Technologies.


Certifications: Microsoft Certified professional (MCP), Microsoft Certified technology specialist (MCTS), Agile-Scrum Master.


Awards: Microsoft Re-connect MVP (GSC Member), Most valuable member at dotnetspider, Most popular curator, Most active curator, featured curator at Microsoft Curah, Editor at dotnetspider.


Microsoft MVP 2014 [ASP.NET/IIS]
Click here for more .NET Tips
-After all Knowledge is an endless entity

You may also be interested in...

Comments and Discussions

 
QuestionAlso one should be aware of Azure Information Protection Pin
Stoffe8122-Nov-17 22:59
memberStoffe8122-Nov-17 22:59 
AnswerRe: Also one should be aware of Azure Information Protection Pin
koolprasadd24-Nov-17 21:48
professionalkoolprasadd24-Nov-17 21:48 
QuestionCan this method do something against... Pin
Nelek25-Nov-15 3:51
protectorNelek25-Nov-15 3:51 
AnswerRe: Can this method do something against... Pin
koolprasadd25-Nov-15 17:03
professionalkoolprasadd25-Nov-15 17:03 
GeneralRe: Can this method do something against... Pin
Nelek26-Nov-15 0:35
protectorNelek26-Nov-15 0:35 
GeneralRe: Can this method do something against... Pin
koolprasadd26-Nov-15 0:43
professionalkoolprasadd26-Nov-15 0:43 
GeneralRe: Can this method do something against... Pin
phil.o16-Oct-17 2:10
mvephil.o16-Oct-17 2:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.190518.1 | Last Updated 25 Nov 2015
Article Copyright 2015 by koolprasadd
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid