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?
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With