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



我正在尝试读取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", ' ');
    }

这个想法可以扩展到所有不可接受的字符,如"#",或"'",或""等等。

相关内容

最新更新