文档.Protect不起作用
本文关键字:不起作用 Protect 文档 | 更新日期: 2023-09-27 18:06:44
嗨,我已经创建了一个asp.net应用程序,其中我正在使用下面的代码片段将asp:panel转换为word文档。
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
tblMain.RenderControl(htw);
if (strType.Equals("Save"))
{
string filename = DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "") + ".doc";
string strPath = Server.MapPath("Attachments") + "''" + filename;
StreamWriter sWriter = new StreamWriter(strPath);
sWriter.Write(sw.ToString());
sWriter.Close();
现在文件保存到指定的文件夹。之后,我将获取相同的文件,用于附加保护密码。我使用了下面的代码。
Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document doc = null;
object missing = System.Reflection.Missing.Value;
object readOnly = false;
object visible = true;
object password = "123";
object fileToOpen = strPath;
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();
doc.Protect(WdProtectionType.wdAllowOnlyComments,ref missing, ref password, ref missing, ref missing);
doc.SaveAs(ref fileToOpen, ref missing, ref missing, ref password, 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)
{
// exception catching
}
finally
{
doc.Close(ref missing, ref missing, ref missing);
wordApp.Quit(ref missing, ref missing, ref missing);
}
但是它会将文件与一个名为filename_files的文件夹一起保存。
删除doc.Protect(WdProtectionType.wdAllowOnlyComments,ref missing, ref password, ref missing, ref missing);
它将只保存文档文件,但不附加密码。
任何想法?请帮我解决这个问题。欢迎大家提出建议。
Thanks in advance.
试试这个:
检查是否有密码
if(doc.HasPassword)
doc.Protect(WdProtectionType.wdAllowOnlyReading,ref missing, ref password, ref missing, ref missing);
else
doc.Protect(WdProtectionType.wdNoProtection,ref missing, ref password, ref missing, ref missing);