为什么路上有非法字符?

时间:2014-01-27 18:49:59

标签: c# file

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

未处理错误异常在路径中显示“非法字符”。 MessageBox显示正确的路径

  C:\Users\Me\Myfile.exe

我尝试执行以下操作:

 commandContent = commandContent.replace(@"\",@"\\");
 result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR

我也尝试了以下内容:

 commandContent = @""+commandContent+"";
 result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR

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

修改

我尝试使用

对路径进行硬编码
 commandContent = @"C:\Users\Me\file.exe";

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

1 个答案:

答案 0 :(得分:6)

我很确定你在字符串commandContent

的结尾或开头有\ n或\ r或\ t或\ ... 你可以做一个

吗?
  System.Text.Encoding.UTF8.GetBytes (commandContent)

并检查每个字节?

也许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);
    }
}
相关问题