title: Failed to access a folder generated by System.IO.Directory.CreateDirectory
body: <p>I'm trying to upload files.</p>
  
  <p>When I post a file, I invoke fileUpload action below.</p>
  
  <pre><code>       [HttpPost]
         public void fileUpload(FormCollection fc)
         {
              string fileName = "";
              string directory = "";
              string uploadPath = "~/Files;
  
              if (Request.Files["Filename"] != null &amp;&amp; Request.Files["Filename"].ContentLength &gt; 0)
              {
                  try
                  {
                      fileName = Path.GetFileName(Request.Files["Filename"].FileName);
                      directory = Path.Combine(Server.MapPath(uploadPath), fileName);
  
  
                      Request.Files["Filename"].SaveAs(directory);
  
                  }
                  catch (Exception msg)
                  {
                      ViewBag.Message = "Failed to upload your file.";
                  }
              }
          }
  </code></pre>
  
  <p><strong>Code above works just fine</strong>. But if I try to create a directory and then try to put the target file into the folder...</p>
  
  <pre><code>       [HttpPost]
         public void fileUpload(FormCollection fc)
         {
  
              string baseFolder = "Files";
              string yyyy = DateTime.Today.Year.ToString();
              string mm = DateTime.Today.Month.ToString();
              string fileName = "";
              string directory = "";
              string uploadPath = "~/" + baseFolder + "/" + yyyy + "/" + mm;
  
              if (Request.Files["Filename"] != null &amp;&amp; Request.Files["Filename"].ContentLength &gt; 0)
              {
                  try
                  {
                      fileName = Path.GetFileName(Request.Files["Filename"].FileName);
                      directory = Path.Combine(Server.MapPath(uploadPath), fileName);
  
                      if (!System.IO.Directory.Exists(directory))
                      {
                          System.IO.Directory.CreateDirectory(directory);
                      }
  
                      Request.Files["Filename"].SaveAs(directory);
  
                  }
                  catch (Exception msg)
                  {
                      ViewBag.Message = "Failed to upload your file.";
                  }
              }
  </code></pre>
  
  <p>This gives me a following error </p>
  
  <p><code>E:\Monarch815MVC\Monarch815MVC\Files\2014\12\me.png' Access to the path is denied.</code></p>
  
  <p>The dynamically generated folders are very suspicious aren't they?</p>
  
  <p>Is there something I missed? Is there something I have to add for the access privilege?</p>
  
  <p>I've googled this issue and found none. They are all talking about "you should give full permission to the folder",</p>
  
  <p>which is not the answer for me.</p>