簡體   English   中英

如果Path包含“#”,則System.Uri無法提供正確的AbsolutePath和LocalPath

[英]System.Uri fails to give correct AbsolutePath and LocalPath if the Path contains “#”

我有C#代碼嘗試使用以下代碼行獲取正在執行的程序集的LocalPath

Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;

這段代碼適用於各種路徑。 它開始失敗,給出正確的AbsolutePathLocalpath因為執行的程序集路徑中包含一個#。

Assembly.GetExecutingAssembly().CodeBase給出"C:\\c#\\ExcelAddin1.1.0\\GSRExcelPlugin\\bin\\Debug\\Common.dll"

但是新的Uri(Assembly.GetExecutingAssembly()。CodeBase).LocalPath給出“C:\\ c”,而它應該給出“C:\\ c#\\ ExcelAddin1.1.0 \\ GSRExcelPlugin \\ bin \\ Debug \\”。

有沒有我需要處理的東西,或者Uri類使用的方式有什么不對嗎?

如果這是.net框架問題,我該如何向Microsoft報告此問題?

System.IO.FileInfo logger = new System.IO.FileInfo(Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath), "settings.config"));

使用EscapedCodeBase而不是CodeBase解決了這個問題。 我知道這已經處理好了,直到我偶然發現它。:)

Uri類表現得如預期。 #不是網址的有效部分。 Imo這是CodeBase屬性的問題。 它返回一個字符串unescaping特殊字符,使其幾乎不可靠。 你的選擇是:

1)始終使用EscapedCodeBase屬性。

var uri = new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath;

2)或者如果您真的必須處理CodeBase屬性(如果這是唯一的選項),請CodeBase獲取轉義部分。

var x = new Uri(Assembly.GetExecutingAssembly().CodeBase);
var uri = x.LocalPath + Uri.UnescapeDataString(x.Fragment).Replace('/', '\\');

3)對於加載的程序集的文件位置,最簡單的方法是使用Location屬性。

var uri = Assembly.GetExecutingAssembly().Location;

這個問題已被多次報道,但MS堅持認為這就是CodeBase 在這里這里這里這里的設計方式

我假設URI函數正在消除銳利#之后的所有內容,因為它認為它是一個錨點。

URI用於識別Internet上的資源,因此您的#字符在任何URI中間都是非法字符。

以這個問題為例,標題是

如果Path包含“#”,則System.Uri無法提供正確的AbsolutePath和LocalPath

但是URL的末尾已經剝離了“#”

系統-URI的失敗到放棄的正確-absolutepath和-了localPath-IF-的路徑,包含

為什么還需要將其轉換為URI。 這3個console.writelines之間唯一的區別是前兩個以File:///為前綴

Console.WriteLine(Assembly.GetExecutingAssembly().CodeBase);  // 1
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
Console.WriteLine(uri);                                       // 2
Console.WriteLine(uri.LocalPath);                             // 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM