Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a file in C#

Tags:

c#

file

asp.net

Seems like it should a really easy topic, all the examples everywhere are just a couple of lines however no decent explainations, and thus I keep running into the same error without a solution.

In short this part of the applicaion runs like so

  1. Pulls images from db
  2. Creates actual images files in a temp folder
  3. creates pdf with images inside of it
  4. now delete images that were created.

Everything works up until the delete. I keep getting the error

InnerException:
System.ArgumentException: URI formats are not supported. at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)...

I have tried a couple different ways to accomplish the delete the latest being:

foreach (string item in TempFilesList)
    {
        path = System.Web.HttpContext.Current.Application["baseWebDomainUrl"] + "/temp/" + item;
        fileDel = new FileInfo(path);
        fileDel.Delete();
    }

and the try before that one was:

foreach (string item in TempFilesList)
    {
        File.Delete(System.Web.HttpContext.Current.Application["baseWebDomainUrl"] + "/temp/" + item);
    }

TempFilesList is an array list containing the paths to the images to delete.

like image 760
corymathews Avatar asked Nov 29 '22 12:11

corymathews


2 Answers

You should try calling Server.MapPath(path) to get the "real" path to the file. Pass that to File.Delete, and it should work (assuming file permissions etc. are correct)

So for example:

foreach (string item in TempFilesList)
{
    path = System.Web.HttpContext.Current.Application["baseWebDomainUrl"] + "/temp/" + item;
    path = Server.MapPath(path);
    fileDel = new FileInfo(path);
    fileDel.Delete();
}
like image 67
David Wengier Avatar answered Dec 06 '22 09:12

David Wengier


You need the actual file path of the file that you've created, not the URL of the path that you've created. Your code creates a path that look something like "http://www.mywebsite.com/location/temp/filename.jpg".

You need something that looks like "C:\MyWorkingFolder\filename.jpg".

I would recommend against using Server.MapPath, however. Since you are creating the files yourself in your own code, you control the location of where the file is being created. Use that, instead. Store it in as an AppSettings key in your web.config.

For example:

string basePath = ConfigurationManager.AppSettings["PdfGenerationWorkingFolder"];
foreach(string item in TempFilesList)
{
  File.Delete(basePath + item);
}
like image 38
Randolpho Avatar answered Dec 06 '22 10:12

Randolpho