【问题标题】:Opening a local Html file within a C# Winforms file在 C# Winforms 文件中打开本地 Html 文件
【发布时间】:2019-09-01 01:01:17
【问题描述】:

我正在尝试打开嵌入在 winform 中的 HTML 文件。 如果我尝试谷歌,它会工作,如果尝试

WebReadmeText.Navigate(@"www.google.com");

但我想做的是打开一个winform,然后打开一个允许用户阅读自述文件的html页面。 这些文件存储在名为 ReadmePages 的项目中的本地文件夹中,文件为 Readme1.html。

我已经把代码放在构造函数里面了,代码如下:

public Readme()
{
    InitializeComponent();

    WebReadmeText.Navigate(@"/ReadmePages/Readme1.html");
}

我使用的具体路径如下

C:\Users\Keith\source\repos\Triangle\ReadmePages

当程序被编译时,这就是输出。

为了安全起见,HTML代码如下:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Readme Volume 1</title>
</head>
<body>
    Triangle Version 1.<Br />
    The longest journeys start with the smallest step, a wise man once said.<Br />
    <Br />
    The First Step.<Br />
    This is a simple program where the Pythagoras' Theorem is calculated and the output displayed.<Br />
    Everyone can remember from school the square of hypotenuse is equal to the sum of the squares of the adjacent and the opposite.<Br />
    In this version I am proofing the formula and to make sure that the theory is correct.<Br />
    <Br />
    In this version I am not making the program object orientated or making it efficient, as I have said it is to validate the proof of concept.<Br />
    The amount of moving parts is zero.<Br />
    The difficulty level is one.<Br />
    <Br />
    </body>
</html>

HTML输出如下

提前感谢您的帮助

【问题讨论】:

  • var myUri = new Uri("File://C:/Users/Keith/source/repos/Triangle/ReadmePages/Readme1.html");。使用完整路径。
  • 这个问题看起来很相似。它有帮助吗? stackoverflow.com/questions/7194851/…
  • @Jimi 使用完整路径意味着程序不能移植到同一系统中的另一个文件夹,更不用说从其他系统运行了。推荐的方法是确保内容位于可执行文件所在的同一目录中,然后在运行时获取可执行文件路径以获取内容
  • @Varun K 使用完整路径并不意味着您必须硬编码路径。只是您需要指定完整路径。该路径可以是变量或任何其他适合的。
  • @Jimi 好酷。我在您的评论中看到硬编码路径并按字面意思解释。

标签: c# winforms


【解决方案1】:

我认为问题在于,WebBrowser 组件不理解该相对路径。

所以我的猜测是,您必须添加完整路径参数,如下所示:

WebReadmeText.Navigate(@"C:\Users\Keith\source\repos\Triangle\ReadmePages\Readme1.html");

在你的情况下,这也可以工作,你不需要硬编码完整路径:

var baseDir = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
WebReadmeText.Navigate($@"{baseDir}\ReadmePages\readme1.html");

【讨论】:

  • 不要使用Directory.GetCurrentDirectory()。你不知道当前目录是什么。
【解决方案2】:

您应该希望从程序集输出文件夹而不是项目文件夹中打开内容文件。例如 bin\debug\ReadmePages\Readme1.html。如果您添加了 Readme1.html 及其父文件夹 ReadmePages 部分,并且已将 Readme1.html 属性“复制到输出目录”标记为“如果较新则复制”,那么实现这一点很容易。 然后您可以使用以下代码(无论构建配置如何 - 调试/发布/ETC。)

            var executablePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            WebReadmeText.Navigate($@"{executablePath}\ReadmePages\Readme1.html");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2018-05-15
    • 2013-12-05
    相关资源
    最近更新 更多