Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if file exist in ASP.NET MVC 4

I am working on an ASP.NET MVC 4 application. I allow users to upload files but I want to save them with different name on the server so I created helper method which should return GUID to be used. Even though it probably will never happen still I want to check if I have a file with the same GUID name so I have this as code :

public static string GetUniqueName(string pathToFile)
        {
            bool IsUnique = false;
            string guid = null;

            while (!IsUnique)
            {
                guid = Guid.NewGuid().ToString("N");
                var path = System.IO.Path.Combine(pathToFile, "login.jpg");

                if (!System.IO.File.Exists(path))
                {
                    IsUnique = true;
                }
            }

            return guid;
        }

as you can see the name of the file is hard coded just for testing purposes, because I know there is such file.

To save the file I use this:

var path = System.IO.Path.Combine(Server.MapPath("~/Content/NewsImages"), fileName);

and it's working properly. So when I tried to call my static method I pass the arbument like this:

string test = Helper.GetUniqueName("~/Content/NewsImages");

but then in debug I saw that

System.IO.Path.Combine(pathToFile, "login.jpg");

returns ~/Content/NewsImages\\login.jpg so I decided to change the argument that I pass to:

string test = Helper.GetUniqueName("~\\Content\\NewsImages");

which now results in ~\\Content\\NewsImages\\login.jpg which seems fine but then in:

            if (!System.IO.File.Exists(path))
            {
                IsUnique = true;
            }

I pass the check, even though I know that such a file exist in the directory that I want to check. How can I fix this?

like image 800
Leron_says_get_back_Monica Avatar asked Dec 05 '13 14:12

Leron_says_get_back_Monica


1 Answers

When calling the helper method you should use Server.MapPath, this will convert from a virtual path to a physical path e.g.

string test = Helper.GetUniqueName(Server.MapPath("~/Content/NewsImages"));
like image 69
James Avatar answered Oct 13 '22 11:10

James