Guest User

Untitled

a guest
Apr 19th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. using System;
  2. using System.Xml.Linq;
  3.  
  4. using DocumentFormat.OpenXml.Packaging;
  5. using DocumentFormat.OpenXml.Wordprocessing;
  6.  
  7. namespace LockDoc
  8. {
  9. /// <summary>
  10. /// Manipulates modification permissions of an OpenXML document.
  11. /// </summary>
  12. class Program
  13. {
  14. /// <summary>
  15. /// Locks/Unlocks an OpenXML document.
  16. /// </summary>
  17. /// <param name="args"></param>
  18. static void Main(string[] args)
  19. {
  20. if (args.Length != 2)
  21. {
  22. Console.WriteLine("Usage: lockdoc lock|unlock filename.docx");
  23. return;
  24. }
  25.  
  26. bool isLock = false;
  27. if (args[0].Equals("lock", StringComparison.OrdinalIgnoreCase))
  28. {
  29. isLock = true;
  30. }
  31. else if (!args[0].Equals("unlock", StringComparison.OrdinalIgnoreCase))
  32. {
  33. Console.Error.WriteLine("Wrong action!");
  34. return;
  35. }
  36.  
  37. WordprocessingDocument doc = WordprocessingDocument.Open(args[1], true);
  38. doc.ExtendedFilePropertiesPart.Properties.DocumentSecurity =
  39. new DocumentFormat.OpenXml.ExtendedProperties.DocumentSecurity
  40. (isLock ? "8" : "0");
  41. doc.ExtendedFilePropertiesPart.Properties.Save();
  42.  
  43. DocumentProtection dp =
  44. doc.MainDocumentPart.DocumentSettingsPart
  45. .Settings.ChildElements.First<DocumentProtection>();
  46. if (dp != null)
  47. {
  48. dp.Remove();
  49. }
  50.  
  51. if (isLock)
  52. {
  53. dp = new DocumentProtection();
  54. dp.Edit = DocumentProtectionValues.Comments;
  55. dp.Enforcement = DocumentFormat.OpenXml.Wordprocessing.BooleanValues.One;
  56.  
  57. doc.MainDocumentPart.DocumentSettingsPart.Settings.AppendChild(dp);
  58. }
  59.  
  60. doc.MainDocumentPart.DocumentSettingsPart.Settings.Save();
  61.  
  62. doc.Close();
  63. }
  64. }
  65. }
Add Comment
Please, Sign In to add comment