C# 如何使用字符串作为HtmlAlityPack文档路径?

C# 如何使用字符串作为HtmlAlityPack文档路径?,c#,visual-studio,visual-studio-2015,html-agility-pack,C#,Visual Studio,Visual Studio 2015,Html Agility Pack,正如问题所暗示的,我试图使用字符串作为HtmlAlityPack DocumentNode路径。当我运行代码时,它会说;路径中存在非法字符 我的代码: 类别: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HtmlAgilityPack; using System.IO; using System.D

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

我的代码:

类别:

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;


        }

    }


}
表格:


该进程由命名空间类\u xlAccountSCRead\u ClassBuild中的ascRead运行。

看起来您正试图以使用C#string literal的方式构建字符串,如下所示:

string cs_literal = @"the_actual_path_goes_here";
注意这里的代码

string your_string = "@" + "\"" +  textBox1.Text + "\"";
…将生成此C#字符串文字的等效值:

string cs_literal = "@\"the_actual_path_goes_here\"";
话虽如此,引号在路径中是非法的,因此“路径中的非法字符”例外。实际上,这里不需要所有转义,因为在C代码中键入的不是字符串文字。只需按原样从
文本框中传递字符串即可:


不清楚DocumentNode path是什么意思。是在
doc.Load(ascDir)行抛出的“非法字符”错误?如果是这样,您能在错误发生时发布
ascDir
的准确值吗?@har07因为OP在值的末尾显式添加了斜杠,所以错误是意料之中的。。。“我不太确定应该如何修复它,所以。”阿列克谢列文科夫认为你是对的。我试图通过运行简单的测试代码来确认,但结果是路径末尾的
`会触发
DirectoryNotFoundException`。此外,OP并没有增加(我相信你知道这一点)。不管怎样,你的评论让我得到了下面的答案。谢谢你的建议解决了我的问题。真不敢相信我竟然没想到要尝试一下。
string cs_literal = "@\"the_actual_path_goes_here\"";
string your_string = textBox1.Text;