求助,C#上传文件时错误:路径中具有非法字符

来源:百度知道 编辑:UC知道 时间:2024/05/15 18:31:37
我是个菜鸟,在写程序时出现错误,路径中具有非法字符。怎么解决阿?!

String http = "//10.118.4.66:7021/dianneng/processuploadfile.jsp?sender_app=ecm&upload_date=2007.01.15&device_type=02&dm_type=02";
WebClient myWebClient = new WebClient();
string fileName = MIS.MisInfo.CurMidDBPath.ToString();//如d:\\111.txt
byte[] responseArray = myWebClient.UploadFile(http, "POST", fileName);
MessageBox.Show("上传文档成功!");
我改成"\\"还是出现“路径中具有非法字符”

1.windows的目录中允许出现的字符是有限定的,不允许出现的字符可以通过Path..GetInvalidFileNameChars()得到,下面是过滤目录中非法字符的方法:


string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
    illegal = illegal.Replace(c.ToString(), ""); 
}

2.也可以使用正则表达式来做替换,如下代码:

string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.