Reputation: 41
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);
I used the code above to download an encrypted image from Google Maps but after it was done downloading, I could not delete that file because it is being used. Can anybody please help me to solve this?
ahhhhhhhhhhhhhhh. very sorry you guys, my mistake. The code above worked but when i tried to draw before delete and this time it does not work. >_< here is the code :
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);
Upvotes: 4
Views: 1078
Reputation: 1582
Is there a particular reason you're calling Dispose
? This might be the cause. If you insist on using dispose, try to delete it before you call dispose. For example . . .
webClient.DownloadFileCompleted += (o, s) =>
{
//if (File.Exists(mapPathName)) discard, see Paolo's comments below . . .
File.Delete(mapPathName);
};
webClient.DownloadFileAsync(uri, mapPathName);
webClient.Dispose();
Also have you considered the using
clause? This is usually prevents those kinds of errors from occurring.
Upvotes: 2
Reputation: 41
i solved my problem. insteading using
gfx.DrawImage(XImage.FromFile(Server.MapPath("\\images\\temp.jpg")), rcImage);
i divided it into 2 line
var img = XImage.FromFile(Server.MapPath("\\images\\temp.jpg"));
gfx.DrawImage(img, rcImage);
and then
img.Dispose;
then i can delete the image :D thank you all.
Upvotes: 0