Click here to Skip to main content
15,886,720 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying this code to password protect a MS Word file.

C#
public static void PasswordProtectDocument(string fileName, string docPassword)
   {
       Application wordAppwordApp = new Application();
       Document doc = null;
       object missing = System.Reflection.Missing.Value;
       object readOnly = false;
       object visible = true;
       object password = docPassword;
       object fileToOpen = fileName;  //fileName is name of file with its full path
       try
       {
           doc = wordApp.Documents.Open(ref fileToOpen, ref missing, ref readOnly, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref visible, ref visible, ref missing, ref missing, ref missing);
           doc.Activate();

           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);
       }
       catch (Exception ex)
       {

       }
       finally
       {
           doc.Close(ref missing, ref missing, ref missing);
           wordApp.Quit(ref missing, ref missing, ref missing);
       }
   }


It is doing also the same but while opening it manually, It is giving this type of dialog box.If we enter the password and click on OK,it is displaying the content.On clicking Cancel,its not displaying anything.But Now the problem is that on clicking Read Only,it is also displaying the content in a read only mode.
This defeats the whole purpose of password protecting a file.So,Instead I want the dialog box not to contain any read only option while opening a password protected MS Word file.

I guess the answer is within the parameters of the Save As or Open function.Kindly help me in completely password protecting a file.
Posted
Updated 23-Oct-13 0:36am
v2

1 solution

Hello friend, here i have shared my method which i used to project my Word file, you can modified that method according to your requirement and resolve your issue.
With the help of this method, i can't open a file without entering the password, even the file is not open in read only mode also.

C#
public override string Protect()
      {
          Application app = new Application();
          Document doc = null;

          object missing = System.Reflection.Missing.Value;
          object readOnly = false;
          object visible = false;
          object _Password = Password;
          object fileToOpen = FileName;
          object enforceStyleLock = false;
          try
          {
              app.Visible = false;
              doc = app.Documents.Open(
                                       ref fileToOpen,
                                       ref missing,
                                       ref readOnly,
                                       ref missing,
                                       ref _Password,
                                       ref missing,
                                       ref missing,
                                       ref missing,
                                       ref missing,
                                       ref missing,
                                       ref missing,
                                       ref visible,
                                       ref visible,
                                       ref missing,
                                       ref missing,
                                       ref missing);

              doc.Activate();
              doc.Password = Password;
              doc.Protect(WdProtectionType.wdAllowOnlyReading,
                              ref missing,
                              ref _Password,
                              ref missing,
                              ref enforceStyleLock);
              doc.ReadOnlyRecommended = false;
              doc.SaveAs(ref fileToOpen,
                          ref missing,
                          ref missing,
                          ref _Password,
                          ref missing,
                          ref _Password,
                          ref enforceStyleLock,
                          ref missing,
                          ref missing,
                          ref missing,
                          ref missing,
                          ref missing,
                          ref missing,
                          ref missing,
                          ref missing,
                          ref missing);
              doc.Close(ref missing, ref missing, ref missing);
              app.Quit(ref missing, ref missing, ref missing);
          }
          catch (System.Exception ex)
          {
              if (ex.GetType().FullName != "System.Exception")
              {
                  if (((ExternalException)(ex)).ErrorCode == -2146822880)
                  {
                      throw new Exception("Document is password protected");
                  }
                  else
                  {
                      throw ex;
                  }
              }
              else
              {
                  throw ex;
              }
          }
          finally
          {
              if (doc != null)
                  Marshal.ReleaseComObject(doc);
              if (app != null)
                  Marshal.ReleaseComObject(app);
              GC.Collect();
              GC.WaitForPendingFinalizers();
              GC.Collect();
              GC.WaitForPendingFinalizers();
          }

          return FileName;
      }


try to unprotect like this...
C#
/// <summary>
        /// Set un-protect Word File
        /// </summary>
        /// <returns></returns>
        public override void UnProtect()
        {
            Application app = new Application();
            Document doc = null;

            object missing = System.Reflection.Missing.Value;
            object readOnly = false;
            object visible = true;
            object _Password = Password;
            object fileToOpen = FileName;

            try
            {
                doc = app.Documents.Open(
                                               ref fileToOpen,
                                               ref missing,
                                               ref readOnly,
                                               ref missing,
                                               ref _Password,
                                               ref missing,
                                               ref missing,
                                               ref _Password,
                                               ref missing,
                                               ref missing,
                                               ref missing,
                                               ref visible,
                                               ref visible,
                                               ref missing,
                                               ref missing,
                                               ref missing);
                doc.Activate();
                //doc.Password = passWord;
                doc.Unprotect(ref _Password);
                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);
                doc.Close(ref missing, ref missing, ref missing);
                Marshal.ReleaseComObject(doc);
                Marshal.ReleaseComObject(app);
            }
            catch (Exception ex)
            {
                //throw ex;
            }
            finally
            {
                if (doc != null)
                    Marshal.ReleaseComObject(doc);
                Marshal.ReleaseComObject(app);
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

        }
 
Share this answer
 
v3
Comments
geniussanjog 31-Oct-13 0:34am    
Hi Tejas,

Thanx for your help.I got though this.Problem Solved.

But my new concern is that can we unprotect a password protected doc or docx file though C#.I now want to remove the password protection from the doc(x) files.I tried this piece of code but its failing to bring about any changes in the file nature.

Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
object nullobj = System.Reflection.Missing.Value;
string pass = Password;
object password = pass;
object FName = fileName;
Microsoft.Office.Interop.Word.Document aDoc = null;
wordApp.Visible = false;
aDoc = wordApp.Documents.Open(ref FName, ref nullobj, ref nullobj, ref nullobj, ref password, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
aDoc.Activate();
if (aDoc.HasPassword)
aDoc.Password = null;
aDoc.SaveAs(ref FName, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
aDoc.Close(ref nullobj, ref nullobj, ref nullobj);
Tejas Vaishnav 31-Oct-13 5:07am    
Hi geniussanjog, can you look at my answer, i have updated and added new method to unprotected the doc file, you might need to do some modification or it might work as it is.
Aboobakkar Siddeq D U 18-Sep-14 2:29am    
It showing error like "no suitable method found to override", what is this error? please tell me how to fix this error?
Tejas Vaishnav 18-Sep-14 8:37am    
I have used this method with Office 2007 interop, which version your are using, and on which method you got that error?
Aboobakkar Siddeq D U 19-Sep-14 0:53am    
In the code itself i'm getting error, I can't run the program, compiling time itself getting error.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900