c# - File.Delete(mapPathName) 不起作用文件正在被使用

标签 c# .net

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

我使用上面的代码从谷歌地图下载了一张加密图片,但下载完成后,我无法删除该文件,因为它正在被使用。 谁能帮我解决这个问题?

啊啊啊啊啊啊啊。非常抱歉你们,我的错。上面的代码有效,但是当我尝试在删除之前绘制时,这次它不起作用。 >_< 这是代码:

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 子句吗?这通常可以防止发生此类错误。

关于c# - File.Delete(mapPathName) 不起作用文件正在被使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14189324/

相关文章:

c# - 在更新语句中使用左连接 where is null

c# - System.TypeLoadException 当我尝试将 JArray 转换为线程中的对象时

c# - 检查延迟加载的属性是否已经实例化

.net - 使用 Nest 客户端在 Elastic Search 中等效的 SQL IN 运算符

c# - 如何在 Surface 4 Pro 中禁用 WPF 平板电脑支持?

c# - SoapExtension System.Configuration.ConfigurationErrorsException in web.config 无法解析属性 'type'的值

c# - 如何将复杂类型传递给 Html.LabelFor?

c# - SendGrid "To"列出列表中所有人可见的电子邮件 ID

.net - [PHP] : Is it possible to access . 通过 PHP NET DLL?

c# - 使用 .NET 4.5 和 IIS 的 MVC 中的应用程序死锁