Example #1
0
		protected override DecryptResult Decrypt(IContentEncryptionUi ui, string sourceFile)
		{			
			object doc = null;

			string tempfile = Path.GetTempFileName();
            var decryptWrapper = new WordApplicationDecryptWrapper();

			try
			{
	            decryptWrapper.CreateHostApplication();
			    DecryptResult result = OpenDocument(ui, sourceFile, out doc, decryptWrapper);
			 
				if (result != DecryptResult.Ok)
				{
					return result;
				}
				  
				//	Modify document passwords, save to -another- temporary file (decryptedPath)
				//	Need to save twice, or for some reason the read/modify passwords get kept
				Logger.LogDebug(string.Format("WordEncryption.Decrypt: Saving attachment to \"{0}\"", sourceFile));
                decryptWrapper.SetOpenPassword(doc, string.Empty);
                decryptWrapper.SetWritePassword(doc, string.Empty);
			    try
			    {
                    decryptWrapper.Save(doc);
			    }
			    catch (InvalidOperationException ex)
			    {
			        // if the document is readonly, Save() throws up UI, so instead it throws an InvalidOperationException, which we ignore...
			        Logger.LogInfo(ex);
			    }

				// If you have Office 2003 & a .docx file the SaveDocumentAs cannot write over the original
				// source file as it is currently locked. As a workaround we save to a temporary file
				// then move the tempfile over the sourceFile
                decryptWrapper.SaveDocumentAs(doc, tempfile, false, string.Empty, string.Empty);
			}
			finally
			{
				if (doc != null)
				{
                    decryptWrapper.CloseDocument(doc, false);
				}
                decryptWrapper.Dispose();
			}

			if (File.Exists(sourceFile))
			{
				File.Delete(sourceFile);
			}
			File.Move(tempfile, sourceFile);	// creates an empty file where sourceFile was -> only do if no error!!
			
			return DecryptResult.Ok;
		}