获取Web项目使用的库中的正确绝对路径
我有一个 asp.net mvc 项目,它在单独的库中使用一些搜索方法。 这个库需要知道我的 lucene 索引文件的位置。
private static string lucenePath = ConfigurationManager.AppSettings["lucenePath"];
public static ColorList SearchColors(Query query) {
return new ColorList(
new IndexSearcher(Path.GetFullPath(lucenePath)),
query);
}
这可以从 web.config 的应用程序关键节点正确读取我配置的 lucenePath 。 但是如何从这个相对路径中获得正确的完整路径呢? Path.GetFullPath 给了我一个完全不正确的路径。
--结论--
如果您想全力以赴,tvanfosson 的答案可能适合您。
然而,我通过使用以下内容让它更加脑死亡:
Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
ConfigurationManager.AppSettings["luceneIndex"].TrimStart('\\'));
这将在调用者的 app.config 中查找名为“path”的应用程序密钥,并将其值与调用者的路径结合起来。 TrimStart() 确保配置文件可以包含或不包含前导 \。
I have an asp.net mvc project that uses some search methods in a seperate library.
This library needs to know the location of my lucene index files.
private static string lucenePath = ConfigurationManager.AppSettings["lucenePath"];
public static ColorList SearchColors(Query query) {
return new ColorList(
new IndexSearcher(Path.GetFullPath(lucenePath)),
query);
}
This correctly reads my configured lucenePath from the web.config's application key node.
But how can I get the correct full path from this relative path? Path.GetFullPath gives me a completely incorrect path.
--Conclusion--
If you want to go full-out, tvanfosson's answer is probably for you.
I, however, kept it a little more brain dead by using the following:
Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
ConfigurationManager.AppSettings["luceneIndex"].TrimStart('\\'));
This will look in the caller's app.config for an appkey called "path" and combine its value to the caller's path. The TrimStart() makes sure that the config file can both contain a leading \ or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您是从一个单独的库引用它,因此您可能必须跳过一堆麻烦才能访问 HttpServerUtitity 或引入一些与难以模拟的类的耦合。 您可能需要考虑使用一个配置类,该配置类从 Web 配置加载属性,并通过构造函数/setter 注入到您的库中。 为了使测试更容易,您可以定义一个可以在单元测试中模拟的接口并让它实现它。 配置类可以使用HttpServerUtility来获取绝对路径并将其存储在内部以供重用。
Since you are referencing this from a separate library, you might have to jump through a bunch of hoops to get access to the HttpServerUtitity or introduce some coupling to classes that are difficult to mock. You might want to consider having a single configuration class that loads properties from the web configuration that gets injected into your library via constructor/setter. To make it easier to test against, you could define an interface that could be mocked in your unit tests and have it implement that. The configuration class could use the HttpServerUtility to obtain the absolute path and store it internally to be reused.