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

StackOverflow https://stackoverflow.com/questions/13365864

سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

Try Application.StartupPath

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

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top