I am working on an ASP.NET MVC 4 application. I allow users to upload files, but I want to save them with a different name on the server, so I created a helper method that should return the GUID to use. Even if this probably never happens, I want to check if I have a file with the same GUID , 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; }
since you can see that the file name is hardcoded for testing purposes only, because I know there is such a file.
To save the file, I use this:
var path = System.IO.Path.Combine(Server.MapPath("~/Content/NewsImages"), fileName);
and it works correctly. Therefore, when I tried to call my static method, I pass the arbument as follows:
string test = Helper.GetUniqueName("~/Content/NewsImages");
but then in debugging I saw that
System.IO.Path.Combine(pathToFile, "login.jpg");
returns ~/Content/NewsImages\\login.jpg , so I decided to change the argument I pass:
string test = Helper.GetUniqueName("~\\Content\\NewsImages");
which now leads to ~\\Content\\NewsImages\\login.jpg , which seems fine, but then in:
if (!System.IO.File.Exists(path)) { IsUnique = true; }
I pass the check, although I know that such a file exists in the directory that I want to check. How can i fix this?
c # relative-path asp.net-mvc-4
Leron
source share