kostinalex
kostinalex

Reputation: 85

Delete file from the project folder no matter where the project is located

The code below won't find the file in the folder. I tried different spellings (with ~, without @, forward slash), but to no avail. In debugger mode VS shows me that the Environment.CurrentDirectory is "bla-bla\IIS".

    string fileName = @"\UploadedFiles\CONF 23 2020-04-03T21-26-36.pdf";
    string path = Path.Combine(Environment.CurrentDirectory, fileName);

    if (File.Exists(path))
    {
        File.Delete(path);
    }

Upvotes: 0

Views: 60

Answers (2)

kostinalex
kostinalex

Reputation: 85

Thanks Fateme Mirjalili. The code that works for me is:

 var filePath = HttpContext.Current.Server.MapPath("/UploadedFiles") 
                + "\\" + "\test.pdf";

            if (File.Exists(filePath))
            {

            }

Upvotes: 0

Fateme Mirjalili
Fateme Mirjalili

Reputation: 746

You can use "DirectoryInfo". For Example:

var directory = new DirectoryInfo($"{Server.MapPath(@"\")}FileUploads");    
var filePath = Path.Combine(directory.ToString(),fileName);    
if (File.Exists(filePath))
{
   File.Delete(filePath);
}

Upvotes: 1

Related Questions