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

- 1,813
- 12
- 26

- 583
- 3
- 9
- 26
-
is this what you're looking for? http://stackoverflow.com/questions/6719293/defining-a-working-directory-for-executing-a-program-c – kenny Nov 13 '12 at 17:46
-
@kenny what? I think you might have forgotten a link – Craig Smith Nov 13 '12 at 17:47
-
yes, but you must have slipped in there I added it 10 second or less later – kenny Nov 13 '12 at 17:48
4 Answers
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.

- 1,813
- 12
- 26
I don't think you'll find the "~" has any significance.
Try Application.StartupPath

- 2,358
- 5
- 27
- 49
-
+1. StartupPath and `Path.Combine` to construct path. (`"~" is "folder for root of the site" in the ASP.Net world...) – Alexei Levenkov Nov 13 '12 at 17:52
Supplying a relative directory, like "Pictures", instead of "~/Pictures/", should do the trick.

- 1,441
- 3
- 17
- 30
-
still same problem, its looking in C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0 – Craig Smith Nov 13 '12 at 17:48
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.

- 123,280
- 14
- 225
- 444
-
-
-
ok, / works for this line Image1.ImageUrl = "~/Pictures/" imageNumber + ".jpg"; – Craig Smith Nov 13 '12 at 17:59