2013-10-02 36 views
2

我目前正在開發一個HTML編輯器使用C#,其中有一個預覽選項,但它不編譯...... 這裏是我的代碼:WPF - 不能在WebBrowser控件打開本地機文件

 string tempPath = System.IO.Path.GetTempPath();//get TEMP folder location 
     tempPath += "htmldev\\"; 
     if (!Directory.Exists(tempPath)) 
     { 
      Directory.CreateDirectory(tempPath); 
     } 
     tempPath += "current.html"; 
     if(File.Exists(tempPath)) 
     { 
      File.Delete(tempPath);//delete the old file 
     } 
     StreamWriter sr = new StreamWriter(tempPath); 
     sr.WriteLine(textHtml.Text);//write the HTML code in the temporary file 
     sr.Close(); 
     previewBrowser.Source = new Uri(tempPath);//When I comment this line my program compiles successfully, and the file is created. 

我也嘗試過使用Navigate()方法,但它沒有工作。

我沒有收到任何錯誤或警告。 編輯:如果我嘗試打開一個網站,如google.com它的作品。

+2

它不會編譯,但你沒有得到任何錯誤或警告?什麼? – tnw

+0

previewBrowser的聲明在哪裏? – franssu

+0

什麼部分不起作用?保存文件的顯示文件? – Sheridan

回答

1

我相信你的XAML不能正確運行,因爲Source="bing.com/"不是Uri構造函數的有效參數(顯然,你的代碼編譯但不運行)。只是刪除Source和它應該運行:

<WebBrowser x:Name="previewBrowser" HorizontalAlignment="Left" 
    Height="593" Margin="651,45,0,0" VerticalAlignment="Top" Width="545"/> 

如果你真的需要一個非空WebBrowser最初,使用Source="about:blank"Source="http://bing.com/"

以下編譯和運行很好。

C#

using System; 
using System.IO; 
using System.Windows; 

namespace WpfWb 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 

      this.Loaded += (s, e) => 
      { 
       var textHtml = "<html><body><b>Hello</b>, World!</body></html>"; 

       string tempPath = System.IO.Path.GetTempPath();//get TEMP folder location 
       tempPath += "htmldev\\"; 
       if (!Directory.Exists(tempPath)) 
       { 
        Directory.CreateDirectory(tempPath); 
       } 
       tempPath += "current.html"; 
       if (File.Exists(tempPath)) 
       { 
        File.Delete(tempPath);//delete the old file 
       } 
       StreamWriter sr = new StreamWriter(tempPath); 
       sr.WriteLine(textHtml);//write the HTML code in the temporary file 
       sr.Close(); 

       previewBrowser.Source = new Uri(tempPath);//When I comment this line my program compiles successfully, and the file is created. 
      }; 
     } 
    } 
} 

XAML

<Window x:Class="WpfWb.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <WebBrowser x:Name="previewBrowser"/> 
</Window>