1 using system; 2 using system. collections. generic; 3 using system. LINQ; 4 using system. text; 5 using system. net. mime; 6 using system. componentmodel; 7 using system. io; 8 using Microsoft. office. interOP. word; 9 Using MSWord = Microsoft. office. interOP. word; 10 using Microsoft. office. tools. word; 11 // using word = Microsoft. office. interOP. word; 12 13 14 namespace consoleapplication415 {16 class program17 {18 static void main (string [] ARGs) 19 {20 string filename = "D: \ test .doc"; 21 string Password = "112233"; 22 protect (password, filename); 23 unprotected (password, filename); 24} 25 26 public static void protect (string password, string filename) 27 {28 MSWord. application wordapp; 29 MSWord. document worddoc; 30 try {31 object missing = type. missing; 32 wordapp = new MSWord. applicationclass (); 33 object filename = Filename; 34 object readonly = false; 35 object isvisible = true; 36 object objfalse = false; 37 wordapp. commandbars ["control toolbox"]. enabled = false; 38 // open the document 39 worddoc = wordapp. documents. open (ref filename, 40 ref missing, ref readonly, ref missing, 41 ref missing, ref missing, 42 ref missing, ref missing, ref isvisible, ref missin G, ref missing); 43 object objprotectpwd = password; 44 object noset = NULL; 45 worddoc. protect2002 (wdprotectiontype. wdallowonlyformfields, ref noset, ref objprotectpwd); 46 worddoc. save (); 47 worddoc. close (ref missing, ref missing, ref missing); 48 wordapp. quit (ref missing, ref missing, ref missing); 49} 50 catch (exception ex) 51 {52} 53} 54 55 public static void unprotected (string password, string File Name) 56 {57 MSWord. application wordapp; 58 MSWord. document worddoc; 59 wordapp = new MSWord. applicationclass (); 60 wordapp. commandbars ["control toolbox"]. enabled = true; 61 object Password = password; 62 object filename = filename; 63 object missing = type. missing; 64 object readonly = false; 65 object isvisible = true; 66 object objfalse = false; 67 worddoc = wordapp. documents. open (ref filename, 68 ref MIS Sing, ref readonly, ref missing, 69 ref missing, 70 ref missing, ref missing, ref isvisible, ref missing, ref missing); 71 worddoc. activate (); 72 // check for password 73 If (worddoc. haspassword) 74 {75 worddoc. password = NULL; 76} 77 // check whether the word document is protected. If no protection function is set, directly remove the password protection 78 If (worddoc. protectiontype! = Wdprotectiontype. wdnoprotection) 79 {80 worddoc. unprotect (ref password); 81} 82 83 worddoc. save (); 84 worddoc. close (ref missing, ref missing, ref missing); 85 wordapp. quit (ref missing, ref missing, ref missing); 86} 87 88} 89}