C# 当文件名中存在空格或(%20)时,未找到CSV文件名

C# 当文件名中存在空格或(%20)时,未找到CSV文件名,c#,.net,c#-4.0,ftp,C#,.net,C# 4.0,Ftp,我正在尝试使用以下代码读取CSV文件以将其上载到数据库表: FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new

我正在尝试使用以下代码读取CSV文件以将其上载到数据库表:

FtpWebRequest reqFTP;
try
{
    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
    reqFTP.UseBinary = true;
    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    int count=0;
    StringBuilder sb = new StringBuilder();
    //GET THE FTP RESPONSE
    using (System.Net.WebResponse tmpRes = reqFTP.GetResponse()) 
    //^^^^^^^^^^^^^^ Error is on this line ^^^^^^^^^^^^^^
    {
        ...
    }
}
当文件名包含空格(调试时有时显示为%20)时,我收到以下错误:

远程服务器返回错误:(550)文件不可用(例如,未找到文件>未访问)

如果文件名不包含空格或%20,则可以正常读取


此任务涉及读取文件解析内容并将数据保存在数据库中,然后将文件移动到另一个文件夹中。

无论何时收集或设置文件名,请尝试以下操作:

if (filename.Contains(" "))
{
    filename= filename.Replace(" ", Uri.HexEscape(' '));
}
如果您计划在以后移动文件,请确保在移动之前通过并执行相反的操作。就你而言:

if (filename.Contains("%20"))
    {
        filename= filename.Replace("%20", ' ');
    }

这个概念可以扩展到所有不可接受的字符,如“#”或“'”或“\”等。

无论何时收集或设置文件名,请尝试以下操作:

if (filename.Contains(" "))
{
    filename= filename.Replace(" ", Uri.HexEscape(' '));
}
如果您计划在以后移动文件,请确保在移动之前通过并执行相反的操作。就你而言:

if (filename.Contains("%20"))
    {
        filename= filename.Replace("%20", ' ');
    }
这个想法可以扩展到所有不可接受的字符,如“#”或“'”或“\”等。

并显示日志。以及
ftpPath+fileName
的实际值。给我们看看日志。以及
ftpPath+fileName
的实际值。