Assembly.CodeBase看起来很有希望,但它是一个UNC路径:
请注意,这是什么近似file uri,不的UNC path。
你可以通过手动进行字符串操作来解决这个问题。 严重。
尝试所有其他方法,你可以找到使之与下面的目录(逐字):
C:\Test\Space()(h#)(p%20){[a&],[email protected],p%,+}.,\Release
这是一个有效的,如果有些不寻常,Windows路径。 (有些人将在那里路径这些字符中的任何一个,你会想你的方法为那些所有工作,对吧?)
可用的代码库(we do not want Location
, right?)的属性然后(上我的Win7与。NET 4):
assembly.CodeBase -> file:///C:/Test/Space()(h#)(p%20){[a&],[email protected],p%,+}.,/Release
assembly.EscapedCodeBase -> file:///C:/Test/Space(%20)(h%23)(p%20)%7B%5Ba%26%5D,[email protected],p%,+%7D.,/Release
你会注意到:
CodeBase
没有逃脱的话,那只是与file:///
前缀常规本地路径和反斜杠替换。因此,它不工作饲料到System.Uri
。
EscapedCodeBase
没有完全逃脱(我做不知道这是一个错误,或者如果这是URI scheme的缺点):
- 注意空格字符(
)如何转化为%20
- 但
%20
序列也转换为%20
! (百分比%
根本没有逃脱)
- 没有人可以重建原来从这个破损的形式!
对于本地文件(这是真正的所有我关心的东西CodeBase
,因为如果该文件是不是本地的,你可能想使用.Location
无论如何,下面的工作对我来说(注意它是不是最漂亮的之一:
public static string GetAssemblyFullPath(Assembly assembly)
{
string codeBasePseudoUrl = assembly.CodeBase; // "pseudo" because it is not properly escaped
if (codeBasePseudoUrl != null) {
const string filePrefix3 = @"file:///";
if (codeBasePseudoUrl.StartsWith(filePrefix3)) {
string sPath = codeBasePseudoUrl.Substring(filePrefix3.Length);
string bsPath = sPath.Replace('/', '\\');
Console.WriteLine("bsPath: " + bsPath);
string fp = Path.GetFullPath(bsPath);
Console.WriteLine("fp: " + fp);
return fp;
}
}
System.Diagnostics.Debug.Assert(false, "CodeBase evaluation failed! - Using Location as fallback.");
return Path.GetFullPath(assembly.Location);
}
我相信一个能想出更好的解决方案,可能是一个甚至可以拿出,做的CodeBase
财产,如果适当的URL加密/解码解决方案这是一条当地的道路,但考虑到人们可以剥掉file:///
我会说这个解决方案足够好,如果肯定真的很难看。
possible dupl [是否有一个.NET Framework方法将文件URI转换为带有驱动器号的路径?](http://stackoverflow.com/questions/278761/is-there-a-net-framework-method-for-converting-文件-Uris-to-paths-with-drive-le) – nawfal 2014-01-10 20:04:25