title: How to check if file exist in ASP.NET MVC 4
body: <p>I am working on an <code>ASP.NET MVC 4</code> 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 <code>GUID</code> to be used. Even though it probably will never happen still I want to check if I have a file with the same <code>GUID</code> name so I have this as code :</p>
  
  <pre><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;
          }
  </code></pre>
  
  <p>as you can see the name of the file is hard coded just for testing purposes, because I know there is such file.</p>
  
  <p>To save the file I use this:</p>
  
  <pre><code>var path = System.IO.Path.Combine(Server.MapPath("~/Content/NewsImages"), fileName);
  </code></pre>
  
  <p>and it's working properly. So when I tried to call my static method I pass the arbument like this: </p>
  
  <pre><code>string test = Helper.GetUniqueName("~/Content/NewsImages");
  </code></pre>
  
  <p>but then in debug I saw that </p>
  
  <pre><code>System.IO.Path.Combine(pathToFile, "login.jpg");
  </code></pre>
  
  <p>returns <code>~/Content/NewsImages\\login.jpg</code> so I decided to change the argument that I pass to:</p>
  
  <pre><code>string test = Helper.GetUniqueName("~\\Content\\NewsImages");
  </code></pre>
  
  <p>which now results in <code>~\\Content\\NewsImages\\login.jpg</code> which seems fine but then in:</p>
  
  <pre><code>            if (!System.IO.File.Exists(path))
              {
                  IsUnique = true;
              }
  </code></pre>
  
  <p>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?</p>