WebClient webClient = new WebClient();
string mapPathName = Server.MapPath("\\images\\temp.jpg");
Uri uri = new Uri(mapLink);
webClient.DownloadFile(uri, mapPathName);
webClient.Dispose();
if (File.Exists(mapPathName))
File.Delete(mapPathName);
我使用上面的代码从谷歌地图下载加密图像,但在完成下载后,我无法删除该文件,因为它正在被使用.
有人可以帮我解决这个问题吗?
ahhhhhhhhhhhhhhh.我很抱歉,我的错误.上面的代码工作,但当我尝试在删除之前绘制,这次它不起作用. > _<
这是代码:
PdfDocument document = new PdfDocument();
document.PageLayout = PdfPageLayout.SinglePage;
document.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = document.AddPage();
// set size
page.Size = PageSize.A4;
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
WebClient webClient = new WebClient();
string mapPathName = Server.MapPath("\\images\\temp.jpg");
Uri uri = new Uri(mapLink);
webClient.DownloadFile(uri, mapPathName);
// defind position to draw the image
XRect rcImage = new XRect(x + 30, y, 410, 300);
// draw the image
gfx.DrawRectangle(XBrushes.Snow, rcImage);
gfx.DrawImage(XImage.FromFile(Server.MapPath("\\images\\temp.jpg")), rcImage);
// save pdf file
string filename = "_HelloWorld.pdf";
string filePath = Server.MapPath(filename);
if (File.Exists(filePath))
File.Delete(filePath);
document.Save(Server.MapPath(filename));
gfx.Dispose();
page.Close();
document.Dispose();
if (File.Exists(mapPathName))
File.Delete(mapPathName);
最佳答案 有没有特别的原因你打电话给Dispose?这可能是原因.如果您坚持使用dispose,请在调用dispose之前尝试删除它.例如 . . .
webClient.DownloadFileCompleted += (o, s) =>
{
//if (File.Exists(mapPathName)) discard, see Paolo's comments below . . .
File.Delete(mapPathName);
};
webClient.DownloadFileAsync(uri, mapPathName);
webClient.Dispose();
您还考虑过使用条款吗?这通常可以防止发生这类错误.