2010-03-17 29 views
2

我有這樣的代碼:爲什麼IsWellFormedOriginalString在文件Uris上失敗?

string uriString = @"C:\Temp\test.html"; 
Uri uri = new Uri(uriString); 
bool goodCond = uri.IsWellFormedOriginalString(); 

但goodCond是假的!我究竟做錯了什麼?


編輯: 感謝約翰和Catdirt。我將集中我的問題:如何將有效文件路徑轉換爲有效文件Uri(使用uri.IsWellFormedOriginalString作爲Uri有效性的指示)? 看看這個:

 DirectoryInfo di = new DirectoryInfo(@"c:\temp"); 
     FileInfo [] fis = di.GetFiles("test.html"); 
     FileInfo fi = fis[0]; 
     string uriString = fi.FullName; 
     Uri uri = new Uri(uriString); 
     bool goodCond = uri.IsWellFormedOriginalString() 

Obviosly fi.fullName是一個很好形成的路徑,但仍然goodCond是壞的!

+0

這是什麼語言/環境? – 2010-03-17 11:26:58

回答

8

您的URI格式不正確。

一個格式良好的例子是file:///C:/Temp/test.html

PS Home:> (new-object Uri 'file:///C:/Temp/test.html').IsWellFormedOriginalString() 
True 
PS Home:> (new-object Uri 'file:///C:\Temp\test.html').IsWellFormedOriginalString() 
False 
PS Home:> (new-object Uri 'C:\Temp\test.html').IsWellFormedOriginalString() 
False 
PS Home:> (new-object Uri 'C:/Temp/test.html').IsWellFormedOriginalString() 
False 
+1

黑客攻擊: Debug.Assert(thePath.StartsWith(@「C:\」)); string reversed = thePath.Replace(@「\」,@「/」); string uriSeed = @「file:///」+ reversed; Uri resUri = new Uri(uriSeed); – Avi 2010-03-17 12:31:09