Add password protection in Microsoft Word document file using C#.Net


Some time we need to protect our document file from unauthorized access. This code to add password protection to Microsoft Word Document using .net

This article to add password lock to MS Word document file. "OpenAndSaveDocument" Method gets two parameter where "fileName" is acomplete path like "C:\test.doc" and "docPassword" the password to opent this file. This method open a word file and save with give password. Next time when you open file you need to enter password


Password protection in word document using C#:



///
/// Protect MS Word Document File using Password
///

public void OpenAndSaveDocument(string fileName,string docPassword)
{
Logger.WriteLogger(DateTime.Now + " : Inside OpenAndSaveDocument \n\r", ConfigUtil.LogFilePath);
Word.ApplicationClass wordApp = new Word.ApplicationClass();
Word.Document doc = null;
object missing = System.Reflection.Missing.Value;
object readOnly = false;
object visible = true;
object password = docPassword;
object fileToOpen = docPath;
Logger.WriteLogger(DateTime.Now + " : File to Open : " + fileToOpen + "\n\r", ConfigUtil.LogFilePath);
try
{
doc = wordApp.Documents.Open(ref fileToOpen, ref missing, ref readOnly, ref missing, ref missing,
ref missing, ref missing, ref password, ref missing, ref missing, ref missing,
ref visible, ref visible, ref missing, ref missing, ref missing);
doc.Activate();
Logger.WriteLogger(DateTime.Now + " : Document activated \n\r", ConfigUtil.LogFilePath);

doc.SaveAs(ref fileToOpen, ref missing, ref missing, ref missing, ref missing, ref password, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
Logger.WriteLogger(DateTime.Now + " : Document saved after insertion of image and password \n\r", ConfigUtil.LogFilePath);
}
catch (Exception ex)
{
Logger.WriteLogger(DateTime.Now + " : Error : " + ex + "\n\r", ConfigUtil.LogFilePath);
}
finally
{
doc.Close(ref missing, ref missing, ref missing);
wordApp.Quit(ref missing, ref missing, ref missing);
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: