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.
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...
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.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)
{
}
finally
{
if (doc != null)
Marshal.ReleaseComObject(doc);
Marshal.ReleaseComObject(app);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}