Search code examples
c#asp.netiotilde-expansion

is there any way to make System.IO.Directory.GetFiles(string) look in the program's directory?


I'm trying to use string[] files = System.IO.Directory.GetFiles("~/Pictures/"); to search a folder in the program for picture files. This will later be used to randomly select a picture to display in an image box.I get an error when it tries to find ~/Pictures because the method is looking in 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\~\Pictures\'. instead. Isn't the "~" going to make it look in the programs directory? How do I make it look in the programs directory if I don't know what it will be until the program is installed? Any help will be appreciated!!


Solution

  • The tilde path is an asp.net construct that represents the root of the currently running asp.net application. It has no meaning outside of the asp.net context -- Directory.GetFiles doesn't know how to work with it. GetFiles does know how to work with a regular filesystem path. So the question becomes: How do we translate the asp.net relative path to one GetFiles can work with. The answer is HttpContext.Current.Server.MapPath.

    I'm not near my webserver right now, but something like

    var serverPath = HttpContext.Current.Server.MapPath("~/Pictures/");
    var files = Directory.GetFiles(serverPath);
    

    should get you started.