我正在下载文件并将更改的文件发送给最终用户在sharepoint 2010中抛出httphandler,但有时我收到错误"该过程无法访问文件' ...'因为它被另一个进程使用了#34;这是我的代码:
string myFile="MypdfFile.pdf";
string downloadFilePath = @"C:\Windows\Temp";
if (!Directory.Exists(downloadFilePath))
{
Directory.CreateDirectory(downloadFilePath);
}
string downloadFilePathAndName = downloadFilePath + "\\" + myFile.Name;
newFile = downloadFilePathAndName;
content = myFile.OpenBinary();
using (PdfReader pdfReader = new PdfReader(content))
{
var fileStream = new FileStream(newFile, FileMode.Create, FileAccess.Write,FileShare.ReadWrite);
var document = new Document(pdfReader.GetPageSizeWithRotation(1));
var writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
for (var i = 1; i <= pdfReader.NumberOfPages; i++)
{
document.NewPage();
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
var importedPage = writer.GetImportedPage(pdfReader, i);
var contentByte = writer.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 12);
string mytext = " ";
contentByte.ShowTextAligned(2, mytext, 100, 200, 0);
contentByte.EndText();
contentByte.AddTemplate(importedPage, 0, 0);
}
document.Close();
writer.Close();
fileStream.Dispose();
fileStream.Close();
pdfReader.Dispose();
pdfReader.Close();
}
我已将FileStream保留在using
语句中,但这也无法解决问题。
答案 0 :(得分:0)
将FileStream
保留在另一个using
内并不足够 - 您还需要在using()
语句中包含 it 。您也不需要Dispose()
using
{/ 1}}。
试试这个(未经测试):
using (var pdfReader = new PdfReader(content))
using (var fileStream = new FileStream(newFile, FileMode.Create, FileAccess.Write,FileShare.ReadWrite))
using (var document = new Document(pdfReader.GetPageSizeWithRotation(1)))
using (var writer = PdfWriter.GetInstance(document, fileStream))
{
document.Open();
for (var i = 1; i <= pdfReader.NumberOfPages; i++)
{
document.NewPage();
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
var importedPage = writer.GetImportedPage(pdfReader, i);
var contentByte = writer.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 12);
string mytext = " ";
contentByte.ShowTextAligned(2, mytext, 100, 200, 0);
contentByte.EndText();
contentByte.AddTemplate(importedPage, 0, 0);
}
// These lines may be unnecessary.
writer.Close();
document.Close();
fileStream.Close();
pdfReader.Close();
}