8

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?

1 Answer 1

21

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"));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It fix the paths. Now it's returning the correct result accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.