The process cannot access the file because it is being used by another process at SharePoint 2010 C# code

Special thanks to Luis.Luis has solved my problem.



Hi Everyone Finally I have solved my problem. problem was that I was saving the zip file on output stream so stream was reading exact bytes and reaching at it's last position and I was attaching same stream to attachment that's why i was getting zero bytes in mail attachment.so solution for this is that seek the position of output stream to begin after saving to zip file and before attaching to it to mail. please refer following code for reference.



Stream outputStream = new MemoryStream();
zipFile.Save(outputStream);
outputStream .Seek(0, SeekOrigin.Begin);
mail.Attachments.Add(new Attachment(outputStream,"ZipFileName" MediaTypeNames.Application.Zip);));

Try moving the position of the stream to it's begiining before sending it to the attachement:



outputStream .Seek(0, SeekOrigin.Begin);


Also before deleting your file make sure you dispose the zipFile object:



zipFile.Dispose()


Or alternately (better) wrap it in a using statement.



Also unless I am missing something if you are using streams, why do you need to save the files to the harddrive? just use the streams, something along the lines of:



var ms = new new MemoryStream();
zipFile.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
mail.Attachments.Add(new Attachment(ms,"ZipFileName" MediaTypeNames.Application.Zip));
zipFile.Dispose()


More: