WPF - 无法在WebBrowser控件中从本地计算机打开文件

时间:2013-10-02 12:35:16

标签: c# html wpf compilation webbrowser-control

我目前正在开发一个带有C#的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.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就可以了。

1 个答案:

答案 0 :(得分:2)

我相信您的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>