views:

448

answers:

2

Hello,

I am using LINQ to retrieve data from the DataBase, the variable name relative to link is "service".

the upDocument is the Id of a FileUpload control.

The objective is to delete the old file, before uploading a new one. This is the code i came up with:

if ((service.image_url != null || service.image_url != "") &&
    (upDocument.FileName.Length != 0 || upDocument.PostedFile.ToString() != ""))
{
     if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(service.image_url)))
     {
          File.Delete(System.Web.HttpContext.Current.Server.MapPath(service.image_url));
     }
}

The problem that I have, is that althought nothing is being loaded to the FileUpload the file is still being deleted. I made a breakpoint and checked it out... and contraty to what i was expecting the FileName.Length is not 0, and the postedFile.ToString() is not "".

How can i make a correct validation?

Thanks in advance.

+4  A: 

Check the HasFile property, like this:

if (!String.IsNullOrEmpty(service.image_url) && upDocument.HasFile) { 
    if (File.Exists(Server.MapPath(service.image_url)))
        File.Delete(Server.MapPath(service.image_url));
}

By the way, inside an ASP.Net page, you don't need to write System.Web.HttpContext.Current, so you can simply write Server.MapPath.

SLaks
thx for the tip, but that's not the answer :(
Marco
Why isn't it the answer?
SLaks
Yeah, his answer sounded correct to me, so you may need to clarify your question.
Sterno
yes, his answer is correct, it was my mistake. I do apologise SLaks.
Marco
A: 

Your problem is that you're deleting the file if service.image_url is null OR if it's "". That condition will always be true, since it can't be both null and "" at the same time.

You should write !String.IsNullOrEmpty(service.image_url), as I wrote in my first answer.

SLaks