为什么路上有非法字符?

Raf*_*ari 1 c# file

....
case "DOWNLOAD":
if (File.Exists(commandContent)) {
MessageBox.Show(commandContent);
result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
result = HttpUtility.UrlEncode(result);          
}
break;
Run Code Online (Sandbox Code Playgroud)

并且未处理的错误异常在路径中显示"非法字符".MessageBox显示正确的路径

  C:\Users\Me\Myfile.exe
Run Code Online (Sandbox Code Playgroud)

我试着做以下事情:

 commandContent = commandContent.replace(@"\",@"\\");
 result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
Run Code Online (Sandbox Code Playgroud)

我也尝试过以下方法:

 commandContent = @""+commandContent+"";
 result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
Run Code Online (Sandbox Code Playgroud)

但这不起作用.而且更奇怪的是它正常工作,但是一旦我将commandContent插入db(使用ajax而不是常规表单提交)的方式进行了一些修改,这个问题出现了?

编辑:

我尝试使用硬编码路径

 commandContent = @"C:\Users\Me\file.exe";
Run Code Online (Sandbox Code Playgroud)

这工作正常.如何强制变量不包含任何非法字符?

Fre*_*dou 6

我很确定你在字符串的结尾或开头都有\n或\ r \n或\ t或... commandContent

你能做一个吗?

  System.Text.Encoding.UTF8.GetBytes (commandContent)
Run Code Online (Sandbox Code Playgroud)

并检查每个字节?

也许ajax调用没有做出正确的字符串/路径

你可以用它来找到哪一个

class Program
{
    static void Main(string[] args)
    {
        var commandContent = "C:\\Users\\Me\\file.exe\n";
        var commandContentBytes = System.Text.Encoding.UTF8.GetBytes(commandContent);
        var invalidPathChars = System.IO.Path.GetInvalidPathChars().Select(x=>Convert.ToByte(x));

        var found = commandContentBytes.Intersect(invalidPathChars);
    }
}
Run Code Online (Sandbox Code Playgroud)