karan k karan k - 2 months ago 25
C# Question

System.IO.File.Exists(fpath) returns false in Chrome, Firefox

I have the following code which works in Internet Explorer, but not in Firefox and Google Chrome.

public ActionResult LogoForm(HttpPostedFileBase file)
{
if (file != null)
{
string fpath = file.FileName;
if (System.IO.File.Exists(fpath))
{
// Logic comes here
}
}
}


In my View I have this:

@using (Html.BeginForm("LogoForm", "LogoEditor", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<text>Logo Image &nbsp;&nbsp;&nbsp;</text>
<input type="file" name="file" id="file" /> <text> &nbsp; &nbsp; &nbsp;</text>
<input type="submit" name="upload" value="Upload" />
}


In case of any file in Firefox and Chrome, the line 'if (System.IO.File.Exists(fpath))' always returns false! It doesn't find the file. Why so?

Answer

file.FileName contains the file path on the client computer, not on the server. You should not use it on the server. The reason this works in IE is because IE happens to send the full path to the file to the server and since you are running both the client and the server on the same machine it works. Chrome and FF for security reasons never send the file path. IIRC they send a dummy path to the server that doesn't exist anywhere. This won't work with IE neither when you deploy your application in IIS and access it remotely.

You should never rely on the path portion of file.FileName. You should only extract the filename and then concatenate it with some path on the server:

Like for example

[HttpPost]
public ActionResult LogoForm(HttpPostedFileBase file)
{
    if (file != null)
    {
        string path = Path.GetFileName(file.FileName);
        string fileName = Path.Combine(Server.MapPath("~/App_Data"), path);
        if (File.Exists(fileName))
        { 
            // logic comes here
        }
    }
}

I would also recommend you checking out the following blog post about uploading files in ASP.NET MVC.