1

I've checked this thread How to get files in a relative path in C#, the directory is in IDE, which is not correct for me. I have a website application, needs to get image files from the same level folder img. I can use following code to get them:

DirectoryInfo path=new DirectoryInfo(@"c:\WebsiteSolution\wwwroot\Chat\img");
FileInfo[] images = path.GetFiles("*");

But I want to use something like .\img to replace the parameter in the first line code, is that possible?

Community
  • 1
  • 1
Steven Zack
  • 4,984
  • 19
  • 57
  • 88

3 Answers3

7

Call the Server.MapPath utility to get the relative path.

DirectoryInfo path = Server.MapPath("~\Chat\img");
Lloyd
  • 2,932
  • 2
  • 22
  • 18
0

For ASP.Net use MapPath - http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx.

Also if you just need to construct path for rendering a page just /Chat/img/My.gif is enough.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
-1

You need to find an anchor - something like Application.ExecutablePath - and then use that anchor with Path.Combine() to reach your image directory.

If your Application.ExecutablePath were: @"c:\WebSiteSolution\wwwroot\chat\code", then you could use string imgPath = Path.Combine(Application.ExecutablePath, @"..\img");

If you have a hard time finding a good anchor, there's a bunch to consider. You can get the path of the executing assembly via Assembly.GetExecutingAssembly().Location

Elmo
  • 6,409
  • 16
  • 72
  • 140
antiduh
  • 11,853
  • 4
  • 43
  • 66
  • I would not use this approach for an ASP.NET application hosted in IIS. For one thing, the ExecutablePath will most likely be some executable under the Windows folder. Also, I belive that IIS makes a shadow copy of assemblies; I'm not sure how that affects the Assembly.Location property, but the value of it may not be what you expect. Using HttpServerUtility.MapPath is the standard way of getting a physical file path for a virtual path. – Dr. Wily's Apprentice Jan 20 '12 at 19:47
  • Thanks for the tips. I've had to deal with this problem a lot in desktop application programming, but I don't do much web programming. – antiduh Jan 20 '12 at 19:48