Set password in Word Document using C# and VB.Net in Wondows Application

PRA
 
on Nov 01, 2019 04:59 AM
Sample_751470.zip
1465 Views

Hi! I have many doc and docx files in computer. Now I want use c# windows application program. When I run it, it must find files and set password without open file. After finished if I open any file its must ask password before open. Can anybody help me?

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 01, 2019 05:40 AM
on Nov 01, 2019 05:41 AM

Hi PRA,

Check this example. Now please take its reference and correct your code.

Namespaces

C#

using Word = Microsoft.Office.Interop.Word;

VB.Net

Imports Word = Microsoft.Office.Interop.Word

Code

C#

private void btnSetPassword_Click(object sender, EventArgs e)
{
    Word._Application objApp = null;
    Word._Document objDoc = null;
    object fileToOpen = "D:\\Doc.docx";
    object objMiss = Type.Missing;
    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);

    try
    {
        objDoc.Password = txtPassword.Text; //set password to open file.
        objDoc.ReadOnlyRecommended = false;
        objDoc.Save(); //save word document.
        MessageBox.Show("Word locked successfully !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

VB.Net

Private Sub btnSetPassword_Click(sender As System.Object, e As System.EventArgs) Handles btnSetPassword.Click
    Dim objApp As Word._Application = Nothing
    Dim objDoc As Word._Document = Nothing
    Dim fileToOpen As Object = "D:\Doc.docx"
    Dim objMiss As Object = Type.Missing
    objApp = New Word.Application()
    objDoc = objApp.Documents.Open(fileToOpen, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss)

    Try
        objDoc.Password = txtPassword.Text
        objDoc.ReadOnlyRecommended = False
        objDoc.Save()
        MessageBox.Show("Word locked successfully !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information)
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    End Try
End Sub

Refer below link for more details.

https://www.codeproject.com/Articles/1058951/Protect-word-document-using-Csharp-and-Word-Automa