Mr. Nicky Mr. Nicky - 1 year ago 109
ASP.NET (C#) Question

ASP.NET Web Forms: How to traverse the files in a project/server folder

My ASP.NET Web forms project has got a folder called "inc" in it and inside there's another folder called "drinks" with images inside. So the absolute path would be something like ~/inc/drinks/.

I'm trying to get all the file names in that exact folder using this function:

private static string[] getImageNames(string imgPath)
string[] names = Directory.GetFiles(imgPath) // <- exception
.Select(path => Path.GetFileName(path))

return names;

Unfortunately that doesn't work and I get an exception:

Could not find a part of the path 'C:\Program Files (x86)\inc\drinks'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files (x86)\inc\drinks'.

The value of the imgPath variable at this point is "../inc/wines/", which should work, but as you can see, the program searches not through the server files, but in my PC's file system on the C: drive.
I tried putting "~/" instead of "../" at the beginning but not luck.

Any suggestions?

Answer Source

Change it to Directory.GetFiles(HttpContext.Current.Server.MapPath(imgPath))

See this answer for more details on Server.MapPath

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download