1 private bool DirectoryExist(string URI) 2 { 3 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(URI)); 4 reqFTP.Credentials = new NetworkCredential("", ""); 5 reqFTP.Method = WebRequestMethods.Ftp.PrintWorkingDirectory; 6 7 reqFTP.UseBinary = true; 8 try 9 { 10 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 11 response.Close(); 12 return true; 13 } 14 catch(Exception ex) 15 { 16 string e=ex.Message; 17 return false; 18 } 19 }
你确定这个是有用的吗?为什么我执行下来,明明没有这个文件夹,缺返回的是true???
File.Exists
正是!!!!
你确定这个是有用的吗?为什么我执行下来,明明没有这个文件夹,缺返回的是true???
可以使用WebRequestMethods.Ftp.ListDirectory试一下,如果文件夹不存在,则line为Null
/// <summary>
/// 判断文件夹是否存在
/// </summary>
/// <param name="dirName"></param>
/// <returns></returns>
public static bool DirectoryIsExist(string dirName)
{
string uri = string.Format("ftp://{0}:{1}/{2}", ftpServerIP, ftpServerPort, dirName);
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string line = reader.ReadLine();
reader.Close();
response.Close();
var result = line != null;
return result;
}
catch (Exception ex)
{
LogHelper.WriteCommonLog(dirName + "目录不存在" + ex.Message);
return false;
}
}
我也碰到这个问题,我已经解决了
/// <summary>
/// 判断文件夹是否存在
/// </summary>
/// <param name="URI"></param>
/// <param name="ftpUserID"></param>
/// <param name="ftpPassword"></param>
/// <returns></returns>
private bool DirectoryExist(string URI, string ftpUserID, string ftpPassword)
{
//hwh 20170616 修复iis设置为framework4.0的时候,ftp目录不存在时返回还是true的问题。
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(URI));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
try
{
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string line = reader.ReadLine();
if (line == null)
{
string e = "目录不存在";
return false;
}
reader.Close();
response.Close();
return true;
}
catch (Exception ex)
{
string e = ex.Message;
return false;
}
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string line = reader.ReadLine();
if (line == null)
{
string e = "目录不存在";
return false;
}
这个方法不对,如果我的目录存在但是内容是空的也会造成 “line == null”