Skip to content

Instantly share code, notes, and snippets.

@tinoji
Created December 25, 2019 06:24
Show Gist options
  • Save tinoji/a9f73fcaddbca579a68825d1d16d6f9c to your computer and use it in GitHub Desktop.
Save tinoji/a9f73fcaddbca579a68825d1d16d6f9c to your computer and use it in GitHub Desktop.
Check file exists and make directories recursively by FTP
public static class FtpUtil
{
/// <returns>exists, ok, error message</returns>
public static (bool, bool, string) FileExists(string ftpUrl, string fileName, string user, string password)
{
WebRequest request = WebRequest.Create(ftpUrl);
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
if (response.StatusCode != FtpStatusCode.OpeningData)
{
return (false, false, response.StatusDescription);
}
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
List<string> files = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
files.Add(line);
line = streamReader.ReadLine();
}
return (files.Any(path => Path.GetFileName(path) == fileName), true, "");
}
}
}
catch (WebException e)
{
FtpWebResponse res = (FtpWebResponse)e.Response;
return (false, false, res.StatusDescription);
}
}
/// <returns>ok, error message</returns>
public static (bool, string) MakeDirectoryRecursively(string ftpUrl, string path, string user, string password)
{
char[] trimChars = { '/' };
path = path.Trim(trimChars);
foreach (string dir in path.Split("/"))
{
if (!string.IsNullOrEmpty(dir))
{
(bool exists, bool ok, string message) = FileExists(ftpUrl, dir, user, password);
if (!ok) return (false, message);
ftpUrl = Path.Combine(ftpUrl, dir);
if (!exists)
{
Console.WriteLine($"ftpUrl: {ftpUrl}");
WebRequest request = WebRequest.Create(ftpUrl);
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
try
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
if (response.StatusCode != FtpStatusCode.PathnameCreated)
{
return (false, response.StatusDescription);
}
}
}
catch (WebException e)
{
FtpWebResponse res = (FtpWebResponse)e.Response;
return (false, res.StatusDescription);
}
}
}
}
return (true, "");
}
}
@tinoji
Copy link
Author

tinoji commented Dec 25, 2019

FluentFTP is much better.
https://github.com/robinrodricks/FluentFTP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment