![](/img/trans.png)
[英]How do I set the default c# file in my Visual Studio Code c# Project?
[英]Using C#, how can I set a Url property to an HTML file in my project?
我有以下代碼:
if (System.IO.File.Exists(htmlLocation))
{
vEarthBrowser.ObjectForScripting = this;
vEarthBrowser.Url = new Uri(htmlLocation);
}
else
{
throw new Exception("HTML file not found!");
}
htmlLocation定義為:
private string htmlLocation = "VirtualEarth.html"
我從中得到的項目應該是正常工作,但是我沒有更改任何代碼。 如果運行此命令,新的Uri()行會給我一個錯誤,“無效的URI:無法確定URI的格式。”
該文件存在(如通過If中的Exists()方法成功傳遞所指示)。 當您希望WebBrowser控件在默認應用程序目錄中加載HTML文件時,引用Url的正確方法是什么?
編輯:
我應該澄清,這是一個winforms項目,而不是Web項目。
嘗試將htmlLocation傳遞給Path.GetFullPath()。
這將自動返回當前exe目錄中文件的絕對路徑。
這是我編寫的輔助函數:
public void LoadPageFromDisk(string filePath)
{
Uri targetPage = null;
string workingPageURI = filePath.Trim();
workingPageURI = Path.GetFullPath(workingPageURI);
if (Uri.TryCreate(workingPageURI, UriKind.RelativeOrAbsolute, out targetPage) == true)
{
webBrowserControl.Navigate(targetPage);
}
}
如果filePath參數為“ localfile.htm”,則Path.GetFullPath將基於當前正在執行的程序集(例如c:\\ Program Files \\ MyApp \\ localFile.htm)返回它的純文本路徑。
然后,Uri.TryCreate將為您提供的絕對文件路徑轉換為有效的文件:// Uri。
最后,WebBrowser.Navigate具有接受Uri的重載。 (需要使用UriKind.RelativeOrAbsolute才能允許TryCreate正確解析絕對文件路徑。)
Uri不會像這樣處理相對路徑。 對於驅動器上的文件,您將需要使用file://格式來創建URI。 將其與Path.GetFullPath()結合起來,您應該走了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.