3

我目前正在用 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,它就可以工作。

4

1 回答 1

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"or 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>
于 2013-10-06T07:27:33.813 回答