如何使用字符串作为 HtmlAgilityPack 文档路径?

How to use a string as an HtmlAgilityPack Document path?

如问题所示,我正在尝试使用字符串作为 HtmlAgilityPack DocumentNode 路径。当我 运行 它说的代码时;路径中的非法字符。

我的代码:

Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.IO;
using System.Dynamic;

namespace Class_xlAccountSCRead_ClassBuild
{
    public class xlAccount_SCProcess
    {
        public static string ascDir { get; set; }
        public static string ascFav { get; set; }
        public static string accountSourceCodeDir;

        public static void ascRead()
        {
            HtmlAgilityPack.HtmlDocument docc = new HtmlAgilityPack.HtmlDocument();
            HtmlDocument doc = new HtmlDocument();
            doc.Load(ascDir);
            ascFav = doc.DocumentNode.SelectNodes("//*[@id=\"favoritesContent\"]/div[2]/div[2]/ul")[0].InnerHtml;


        }

    }


}

表格:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Dynamic;
using HtmlAgilityPack;

namespace xlAccountSCRead_ClassBuild
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

            Class_xlAccountSCRead_ClassBuild.xlAccount_SCProcess.ascDir = "@" + "\"" + textBox1.Text + "\"";

            //await Task.Delay(100);
            Class_xlAccountSCRead_ClassBuild.xlAccount_SCProcess.ascRead();

            textBox2.Text = Class_xlAccountSCRead_ClassBuild.xlAccount_SCProcess.ascFav;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Class_xlAccountSCRead_ClassBuild.xlAccount_SCProcess.ascDir = "@" + "\"" +  textBox1.Text + "\"";

            label1.Text = Class_xlAccountSCRead_ClassBuild.xlAccount_SCProcess.ascDir;
        }
    }
}

进程是 运行 由命名空间 Class_xlAccountSCRead_ClassBuild 中的 ascRead。

看起来您正在尝试按照使用 C# 字符串文字的方式构建字符串,如下所示:

string cs_literal = @"the_actual_path_goes_here";

注意你的代码在这里...

string your_string = "@" + "\"" +  textBox1.Text + "\"";

...将生成此 C# 字符串文字的等效项:

string cs_literal = "@\"the_actual_path_goes_here\"";

话虽如此,引号在路径中是非法的,因此 "illegal characters in path" 异常。实际上,您不需要在此处进行所有转义,因为它不是您在 C# 代码中键入的字符串文字。只需按原样传递 TextBox 中的字符串 :

string your_string = textBox1.Text;