簡體   English   中英

File.Delete(mapPathName)不起作用正在使用文件

[英]File.Delete(mapPathName) doesn't work file is being used

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);

我使用上面的代碼從Google Maps下載了加密的圖像,但下載完成后,由於使用該文件,我無法刪除該文件。 有人可以幫我解決這個問題嗎?

ahhhhhhhhhhhhh。 非常抱歉,我的錯誤。 上面的代碼有效,但是當我嘗試在刪除之前繪制時,這一次它不起作用。 > _ <這是代碼:

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();

您還考慮過using子句嗎? 通常,這可以防止發生此類錯誤。

我解決了我的問題。 代替使用

gfx.DrawImage(XImage.FromFile(Server.MapPath("\\images\\temp.jpg")), rcImage);

我把它分成兩行

var img = XImage.FromFile(Server.MapPath("\\images\\temp.jpg"));
gfx.DrawImage(img, rcImage);

然后

img.Dispose;

然后我可以刪除圖像:D謝謝大家。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM