2

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!!

Reacher Gilt
  • 1,813
  • 12
  • 26
Craig Smith
  • 583
  • 3
  • 9
  • 26

4 Answers4

5

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.

Reacher Gilt
  • 1,813
  • 12
  • 26
1

I don't think you'll find the "~" has any significance.

Try Application.StartupPath

Black Light
  • 2,358
  • 5
  • 27
  • 49
0

Supplying a relative directory, like "Pictures", instead of "~/Pictures/", should do the trick.

Steven Lemmens
  • 1,441
  • 3
  • 17
  • 30
0

Just use System.IO.Directory.GetFiles('Pictures'). The path separator on Windows is \, not /, and directories below the current one are just referenced as relative path locations.

Ken White
  • 123,280
  • 14
  • 225
  • 444