首页 > 解决方案 > 如何在 C# winforms 应用程序中将 html 文件保存到 MyDocuments

问题描述

我有一个编写 html 文件并将其打开到网络浏览器的函数。但是,当我打包和部署应用程序时,它不会打开并说访问被拒绝。我被告知我需要将 html 文件写入计算机 mydocuments 并在那里打开它。有关如何执行此操作的任何想法,以便我可以解决此权限错误?这是我编写 html 文件的函数:

private void PrintReport(StringBuilder html)
{
    // Write (and overwrite) to the hard drive using the same filename of "Report.html"
    try
    {
        // A "using" statement will automatically close a file after opening it.
        // It never hurts to include a file.Close() once you are done with a file.
        using (StreamWriter writer = new StreamWriter("Report.html"))
        {
            writer.WriteLine(html);
        }
        System.Diagnostics.Process.Start(@"Report.html"); //Open the report in the default web browser
        
    }
    catch (Exception ex)
    {
        MessageBox.Show(message + ex.Message, "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

标签: c#htmlwinforms

解决方案


private void PrintReport(StringBuilder html)
{
    // Write (and overwrite) to the hard drive using the same filename of "Report.html"
    try
    {
        // A "using" statement will automatically close a file after opening it.
        // It never hurts to include a file.Close() once you are done with a file.
        using (StreamWriter writer = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Report.html"))
        {
            writer.WriteLine(html);
        }
        System.Diagnostics.Process.Start(@"Report.html"); //Open the report in the default web browser
        
    }
    catch (Exception ex)
    {
        MessageBox.Show(message + ex.Message, "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

推荐阅读