views:

3070

answers:

4

I'm trying to get the absolute path of certain files in a C# class. Server.MapPath works great of course for ASPX and their code-behind pages, but that doesn't exist in another class file. I tried HostingEnvironment.MapPath(), but that complains that the relative virtual path isn't allowed. Any thoughts?

System.Web is already imported.

+7  A: 

The ServerUtility class is available as an instance in your HttpContext. If you're in an environment where you know it'll be executed inside the ASP.Net pipeline, you can use

HttpContext.Current.Server.MapPath()

You'll have to import System.Web though.

womp
Perfect. I didn't realize I had the HttpContext.Current. Thanks.
Chet
A: 

Can't you just add a reference to System.Web and then you can use Server.MapPath ?

Dan Diplo
Not in external classes.
infamouse
Sure you can add the reference to an external class; but obviously you need to use it in the context of a server request so HttpContext is not null.
Dan Diplo
A: 

Have you tried:

System.IO.Path.GetFullPath()

MSDN Link

brianng
-1: For not knowing what Server.MapPath does, but answering anyway.
John Saunders
Oops, think I read this question the same way David did.
brianng
A: 
System.Reflection.Assembly.GetAssembly(type).Location

IF the file you are trying to get is the assembly location for a type. But if the files are relative to the assembly location then you can use this with System.IO namespace to get the exact path of the file.

David McEwing
-1: What led you to believe he wanted the location of an assembly?
John Saunders
He said "certain files" he didn't specify the location or nature of the files, thus knowing the assembly location and being able to work relative to that path can be helpful. Of course if he actually stated he was still in a HttpContext then I wouldn't have bothered answering.
David McEwing