FTP判斷ftp上是否有檔案目錄,沒有就建立的具體案例
/// <summary>
/// 判斷ftp上是否有指定的檔案目錄,沒有建立
/// </summary>
/// <param name="ftpPath">指定路徑</param>
public void FtpDirectoryAndFile(string ftpPath)
{
int start = "ftp://192.168.1.198:21/".Length;
int end = ftpPath.LastIndexOf("/") - start;
string fullDir = ftpPath.Substring(start, end);
string[] dirs = fullDir.Split('/');
if (dirs != null && dirs.Length > 0)
{
string curDir = "ftp://192.168.1.198:21/";
for (int i = 0; i < dirs.Length; i++)
{
string dir = dirs[i];
if (dir != null && dir.Length > 0)
{
bool isContained = FtpDirIsExists(curDir, dir);
if (isContained)
{
curDir += dir + "/";
continue;
}
else
{
FtpMakeDir(curDir + dir);
curDir += dir + "/";
}
}
}
}
}
/// <summary>
/// 判斷ftp上的檔案目錄是否存在
/// </summary>
/// <param name="dirName">要判斷的ftp上的檔案目錄路徑</param>
/// <param name="folderName">ftp上的檔案目錄路徑中是否包含該資料夾名稱</param>
/// <returns>true 包含,false 不包含</returns>
public static bool FtpDirIsExists(string dirName, string folderName)
{
//string url = "ftp://" + FtpServerIP + "/" + dirName;
FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(new Uri(dirName));
ftpWebRequest.UseBinary = true;
ftpWebRequest.Credentials = new NetworkCredential("wlj", "778822jj,.");
ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
StreamReader streamReader = null;
Stream responseStream = null;
bool isContained = false;
try
{
using (FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse())
{
responseStream = ftpWebResponse.GetResponseStream();
streamReader = new StreamReader(responseStream);
string nameList = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
string[] nameArr = nameList.Replace("\r\n", "#").Split(new string[] { "#"}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < nameArr.Length; i++)
{
if (nameArr[i].Equals(folderName))
{
isContained= true;
break;
}
}
return isContained;
}
}
catch (Exception ex)
{
if (streamReader != null)
{
streamReader.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
return false;
}
}
/// <summary>
/// 在FTP上建立目錄
/// </summary>
/// <param name="dirName">要建立的目錄名</param>
public bool FtpMakeDir(string dirName)
{
FtpWebResponse response = null;
StreamReader reader = null;
try
{
//string uri = FtpServerIP + DateTime.Now.ToString("yyyyMMddHHmmss") + fileInfo.Name;
FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(dirName));
reqFTP.Credentials = new NetworkCredential("wlj", "778822jj,.");
//reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
response = (FtpWebResponse)reqFTP.GetResponse();
reader = new StreamReader(response.GetResponseStream());
string returnValue = reader.ReadToEnd();
response.Close();
reader.Close();
return true;
}
catch (Exception ex)
{
if (response != null)
{
response.Close();
}
if (reader != null)
{
reader.Close();
}
return false;
}
}
使用 測試如下
string ss = "ftp://192.168.1.198:21/2018/11/222.pdf";
FtpDirectoryAndFile(ss);
string sss = "333";