-2

Sorry to ask this again, I have already seen this.

I am using the following code to create multiple directories from a single full path, but it isn't doing anything. My compiler enters the conditions and runs the command, but doesn't create directory. I don't know what is wrong.

if (!Directory.Exists(@"~/Documents/2/images/"))
{
    Directory.CreateDirectory(@"~/Documents/2/images/");
}
Community
  • 1
  • 1
Learner
  • 776
  • 6
  • 14
  • 40
  • 2
    This is probably creating a directory called `~` as a subdirectory of the current directory. Is that not what you're expecting it to do? – Greg Hewgill May 13 '15 at 00:27
  • oh no sorry, i am building in asp.net web application and ~ is the root directory of my solution – Learner May 13 '15 at 00:28
  • 2
    You might believe that `~` is the "root directory of your solution", but the `Directory.CreateDirectory()` function has no such opinion. – Greg Hewgill May 13 '15 at 00:28
  • but i gives me the actual path which is in c:\ drive – Learner May 13 '15 at 00:29
  • 2
    Look into [`HttpServerUtility.MapPath`](https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx) – Matt Johnson-Pint May 13 '15 at 00:33
  • You don't have to do the check, if the directory already exists `CreateDirectory` doesn't do anything. – Ron Beyer May 13 '15 at 00:55
  • Try it with full path... like Directory.CreateDirectory(@"C:/abc/doc/2/images/") If you are still not able to create the directory then probably the reason could be is, your *User* is not having *write* rights on that particular drive/directory. So try with changing the directory. Let's say try it with D:/abc/def etc. – Amnesh Goel May 13 '15 at 01:04

1 Answers1

3

The problem here seems to be a missconception with the tilde "~" symbol, in ASP.NET applications the tilde is frequently used to designate the application root directory but it doesn't work everywhere, in fact, the "~" symbol only works on URLs so @"~/Documents/2/images/" is not a path, it's a URL that represents something like http://myserver.com/MyApplicationRoot/Documents/2/images/

To use the "~" in this context you must map the URL to a physical path, you can do so with Server.MapPath(@"~/Documents/2/images/"), which will return something like "c:\inetpub\wwwroot\myApp\Documents\2\images\", and that's what you should pass on to CreateDirectory

A "~" when passed to a physical path will be interpreted literally and will refer to a folder named "~"

Eduardo Wada
  • 2,606
  • 19
  • 31