We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Not able to add password to pdf file

// I am creating file using file byte array, bind password to it and attached this file to email, i got below error

private string GetFilePath(string FileName,Byte[] fileBytes, string fileExtension)
string cfgTempDirectory = @“C:\temp”;
bool cfgEnablePasswordProtectedAttachment = false; //config
string tempSourceFile = “”;
string tempDestinationFile = “”;
string strcfgEnablePasswordProtectedAttachment = “”;
string AsposeLicenseFilePath = “”;
string UserPassword=“somepassword”;

            fileExtension = fileExtension.Replace(".", "");
            tempSourceFile = cfgTempDirectory + "\\PN" + Guid.NewGuid().ToString().Replace("-", "") + DateTime.Now.ToString("ddmmyyyHHmmssfff") + "." + fileExtension;                
            tempDestinationFile = cfgTempDirectory + "\\" + Path.GetFileNameWithoutExtension(FileName) + "_" + RandomNumber() + Path.GetExtension(FileName);               
            File.WriteAllBytes(tempSourceFile, fileBytes);
			using (PdfFileSecurity fileSecurity = new PdfFileSecurity())
                fileSecurity.EncryptFile(UserPassword, "somekey", DocumentPrivilege.Print, KeySize.x256, Algorithm.AES);                   
                fileSecurity.Save(tempDestinationFile);   /// error in this line, System.IO.IOException: The process cannot access the file 'F:\somefolder\Attachment\77830_PMS_Order_CONFIRMATION_20211102172649293.pdf' because it is being used by another process.                 


Are you sure that you are receiving a valid PDF document in byte array? Please share the sample PDF document which you are obtaining after below step:

File.WriteAllBytes(tempSourceFile, fileBytes);

We will test the scenario in our environment and address it accordingly.

This happened randomly


It is hard to determine the error cause without replicating the issue in our environment. There is a possibility that bytes are getting corrupted in your code routine. Please try to share a sample console application that is able to reproduce the error. This way we can try to replicate it in our environment and address it accordingly.