当前位置:   article > 正文

C# WPF(.NET Framework)窗口使用HTML页面[外部文件相对路径式]_wpf 加载相对路径文件

wpf 加载相对路径文件

在后台代码中,使用Navigate方法加载外部HTML文件:

using System;
using System.Windows;

namespace MyApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // 在窗口加载时加载HTML文件
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // 加载外部HTML文件
            string currentDirectory = Environment.CurrentDirectory;
string htmlFilePath = Path.Combine(currentDirectory, "file.html");

webBrowser.Navigate(new Uri(htmlFilePath));

        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

代码使用 Environment.CurrentDirectory 获取当前应用程序的目录,然后使用 Path.Combine 将目录和 HTML 文件名拼接起来,最终得到完整的文件路径。然后,通过 webBrowser.Navigate 方法加载该文件。

如果是相对目录下的子目录内,啧可将代码修改为如下样式:

string currentDirectory = Environment.CurrentDirectory;
string htmlFilePath = Path.Combine(currentDirectory, "docs", "TileSize.html");

webBrowser.Navigate(new Uri(htmlFilePath));
  • 1
  • 2
  • 3
  • 4

请确保在 Path.Combine 方法中按照 “docs” 和 “example.html” 的顺序提供文件夹和文件名。

这样做可以加载位于当前目录下的 docs/example.html 文件。如果还有其他问题,请随时提问。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/257894
推荐阅读
相关标签
  

闽ICP备14008679号