我怎么能转换大会。codeBase的成C#中的文件系统路径?文件系统、路径、大会、我怎么能

2023-09-03 00:43:37 作者:你媚你魅你昧你妹

我有一个存储在 \模板文件夹模板旁边的DLL和EXE。

I have a project that stores templates in a \Templates folder next to the DLLs and EXE.

我想在运行时确定该文件的路径,但使用的是将在生产内部的单元测试以及工作方法(我不希望禁用阴影复制在NUnit的!)

I want to determine this file path at runtime, but using a technique that will work inside a unit test as well as in production (and I don't want to disable shadow-copying in NUnit!)

Assembly.Location 是没有好,因为它的NUnit下运行时返回影像复制程序集的路径。

Assembly.Location is no good because it returns the shadow-copied assembly's path when running under NUnit.

Environment.CommandLine 也是有限的使用,因为在NUnit的等它返回的路径,NUnit的,不是我的项目。

Environment.CommandLine is also of limited use because in NUnit et al it returns the path to NUnit, not to my project.

大会codeBase的看起来很有希望,但它是一个UNC路径:

Assembly.CodeBase looks promising, but it's a UNC path:

file:///D:/projects/MyApp/MyApp/bin/debug/MyApp.exe

现在我的可以的把它变成使用字符串操作本地文件系统路径,但我怀疑有做埋在.NET框架某处的一个更清洁的方式。任何人都知道这样做的推荐方法?

Now I could turn this into a local filesystem path using string manipulation, but I suspect there's a cleaner way of doing it buried in the .NET framework somewhere. Anyone know a recommended way of doing this?

(如果UNC路径不是文件抛出异常:/// URL是在这种情况下绝对没问题)

(Throwing an exception if the UNC path is not a file:/// URL is absolutely fine in this context)

推荐答案

您需要使用System.Uri.LocalPath:

You need to use System.Uri.LocalPath:

string localPath = new Uri("file:///D:/projects/MyApp/MyApp/bin/debug/MyApp.exe").LocalPath;

所以,如果你想在当前执行的程序集的原始位置:

So if you want the original location of the currently executing assembly:

string localPath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;