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