Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying relative file location in web.config for use by standard C# class library

Tags:

c#

asp.net

I'm struggling to find a way of specifying a file location in web.config appSettings that avoids using hard-coded paths but allows a non-'web aware' C# library to find a file.

The C# library uses standard File.Open, File.Exists methods, etc. to operate on a data file, which is stored in my web application (ASP.NET MVC) tree, e.g. under:

\content\data\MyDataFile.txt

Requirements:

  • I want to be able to specify my path like, e.g.:
        <appSettings>
this-->     <add key="MyFileLocation" value="~\content\data\MyDataFile.txt" />
not -->     <add key="MyFileLocation" value="c:\inetpub\wwwroot\foo\content\data\MyDataFile.txt" />
        </appSettings>
  • I don't want the C# library to be aware of the web application it's being used in, as it is used in other software, and the web application has no need to know about the configuration of the C# library so I don't really want to pass config info between the layers if possible.

Any suggestions on how I can do this cleanly? Thanks!

like image 496
Tim Croydon Avatar asked Jan 06 '11 15:01

Tim Croydon


1 Answers

You could use Path.Combine to combine AppDomain.CurrentDomain.BaseDirectory and your relative path.

This will give you a path relative to the ASP.NET root directory (~/) in an ASP.NET app, or a path relative to the directory containing the executable in a WinForms or Console application.

like image 142
Joe Avatar answered Sep 22 '22 14:09

Joe