How to check FTP connection? - c#

Is there a simple, fast way to check that a FTP connection (includes host, port, username and password) is valid and working? I'm using C#. Thank you.

try something like this:
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create("ftp://ftp.google.com");
requestDir.Credentials = new NetworkCredential("username", "password");
try
{
WebResponse response = requestDir.GetResponse();
//set your flag
}
catch
{
}

this is the method I use, let me know if you know a better one.
/*Hola
Este es el metodo que utilizo si conoces uno mejor hasmelo saber
Ubirajara 100% Mexicano
isc.erthal#gmail.com
*/
private bool isValidConnection(string url, string user, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(user, password);
request.GetResponse();
}
catch(WebException ex)
{
return false;
}
return true;
}

This might be useful.
public async Task<bool> ConnectAsync(string host, string user, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host);
request.Credentials = new NetworkCredential(user, password);
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false; // useful when only to check the connection.
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse) await request.GetResponseAsync();
return true;
}
catch (Exception)
{
return false;
}
}

Use either System.Net.FtpWebRequest or System.Net.WebRequestMethods.Ftp to test your connection using your login credentials. If the FTP request fails for whatever reason the appropriate error message will be returned indicating what the problem was (authentication, unable to connect, etc...)

You could try using
System.Net.FtpWebRequest and then just check the GetResponseStream method.
So something like
System.Net.FtpWebRequest myFTP = new System.Net.FtpWebRequest
//Add your credentials and ports
try
{
myFTP.GetResponseStream();
//set some flags
}
catch ex
{
//handle it when it is not working
}

This is from the msdn site to diplay files from a server
public static bool DisplayFileFromServer(Uri serverUri)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
try
{
byte [] newFileData = request.DownloadData (serverUri.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
return true;
}

Related

How to check file exists in FTP c# [duplicate]

I need to use FtpWebRequest to put a file in a FTP directory. Before the upload, I would first like to know if this file exists.
What method or property should I use to check if this file exists?
var request = (FtpWebRequest)WebRequest.Create
("ftp://ftp.domain.com/doesntexist.txt");
request.Credentials = new NetworkCredential("user", "pass");
request.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode ==
FtpStatusCode.ActionNotTakenFileUnavailable)
{
//Does not exist
}
}
As a general rule it's a bad idea to use Exceptions for functionality in your code like this, however in this instance I believe it's a win for pragmatism. Calling list on the directory has the potential to be FAR more inefficient than using exceptions in this way.
If you're not, just be aware it's not good practice!
EDIT: "It works for me!"
This appears to work on most ftp servers but not all. Some servers require sending "TYPE I" before the SIZE command will work. One would have thought that the problem should be solved as follows:
request.UseBinary = true;
Unfortunately it is a by design limitation (big fat bug!) that unless FtpWebRequest is either downloading or uploading a file it will NOT send "TYPE I". See discussion and Microsoft response here.
I'd recommend using the following WebRequestMethod instead, this works for me on all servers I tested, even ones which would not return a file size.
WebRequestMethods.Ftp.GetDateTimestamp
Because
request.Method = WebRequestMethods.Ftp.GetFileSize
may fails in some case (550: SIZE not allowed in ASCII mode), you can just check Timestamp instead.
reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password);
reqFTP.UseBinary = true;
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;
FtpWebRequest (nor any other class in .NET) does not have any explicit method to check a file existence on FTP server. You need to abuse a request like GetFileSize or GetDateTimestamp.
string url = "ftp://ftp.example.com/remote/path/file.txt";
WebRequest request = WebRequest.Create(url);
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
request.GetResponse();
Console.WriteLine("Exists");
}
catch (WebException e)
{
FtpWebResponse response = (FtpWebResponse)e.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
Console.WriteLine("Does not exist");
}
else
{
Console.WriteLine("Error: " + e.Message);
}
}
If you want a more straightforward code, use some 3rd party FTP library.
For example with WinSCP .NET assembly, you can use its Session.FileExists method:
SessionOptions sessionOptions = new SessionOptions {
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "username",
Password = "password",
};
Session session = new Session();
session.Open(sessionOptions);
if (session.FileExists("/remote/path/file.txt"))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Does not exist");
}
(I'm the author of WinSCP)
You can use WebRequestMethods.Ftp.ListDirectory to check if a file exist, no need for nasty try catch mechanism.
private static bool ExistFile(string remoteAddress)
{
int pos = remoteAddress.LastIndexOf('/');
string dirPath = remoteAddress.Substring(0, pos); // skip the filename only get the directory
NetworkCredential credentials = new NetworkCredential(FtpUser, FtpPass);
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(dirPath);
listRequest.Method = WebRequestMethods.Ftp.ListDirectory;
listRequest.Credentials = credentials;
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
string fileToTest = Path.GetFileName(remoteAddress);
while (!listReader.EndOfStream)
{
string fileName = listReader.ReadLine();
fileName = Path.GetFileName(fileName);
if (fileToTest == fileName)
{
return true;
}
}
}
return false;
}
static void Main(string[] args)
{
bool existFile = ExistFile("ftp://123.456.789.12/test/config.json");
}
I use FTPStatusCode.FileActionOK to check if file exists...
then, in the "else" section, return false.

The remote server returned an error: (404) Not Found. when doing a HttpWebResponse

I am having an issue with my code as I have to verify the status of some websites in order to notify if they are working or not. I can successfully check this for a number of websites, however for a particular one it is always returning 404 Not Found, even though the site is up and I can view it if I try to open the page on the browser, this is my code:
public HttpStatusCode GetHeaders(string url, bool proxyNeeded)
{
HttpStatusCode result = default(HttpStatusCode);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = new NetworkCredential(username, password, domain);
if (proxyNeeded)
{
IWebProxy proxy = new WebProxy("127.0.0.1", port_number);
proxy.Credentials = new NetworkCredential(username, password, domain);
request.Proxy = proxy;
}
try
{
var response = (HttpWebResponse) request.GetResponse();
result = response.StatusCode;
response.Close();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
WebResponse resp = e.Response;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
//TODO: capture the exception!!
}
}
}
return result;
}
The exception does not tell me anything different than "Not Found" which really confuses me as I don't know where else to look.The URL failing is: http://cbprod-app/InterAction/home
If I request the page without setting the proxy, comes back with an "401 Not authorized" as it requires the proxy authentication to be displayed, I am running out of ideas, any suggestion about what am I doing wrong?
Thank you very much in advance.

Deleting file from FTP in C#

My program can upload files into an FTP server using this code:
WebClient client = new WebClient();
client.Credentials = new System.Net.NetworkCredential(ftpUsername, ftpPassword);
client.BaseAddress = ftpServer;
client.UploadFile(fileToUpload, WebRequestMethods.Ftp.UploadFile, fileName);
Right now I need to delete some files and I can't do that right. What should I use instead of
client.UploadFile(fileToUpload, WebRequestMethods.Ftp.UploadFile, fileName);
You'll need to use the FtpWebRequest class to do that one, I think.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
//If you need to use network credentials
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
//additionally, if you want to use the current user's network credentials, just use:
//System.Net.CredentialCache.DefaultNetworkCredentials
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Delete status: {0}", response.StatusDescription);
response.Close();
public static bool DeleteFileOnFtpServer(Uri serverUri, string ftpUsername, string ftpPassword)
{
try
{
// The serverUri parameter should use the ftp:// scheme.
// It contains the name of the server file that is to be deleted.
// Example: ftp://contoso.com/someFile.txt.
//
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//Console.WriteLine("Delete status: {0}", response.StatusDescription);
response.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
Usage:
DeleteFileOnFtpServer(new Uri (toDelFname), user,pass);
You should use FtpWebRequest when you need to delete files:
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Delete status: {0}",response.StatusDescription);
response.Close();
ref:
http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx
public static bool DeleteFileOnServer(Uri serverUri)
{
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Delete status: {0}",response.StatusDescription);
response.Close();
return true;
}

C# Getting proxy settings from Internet Explorer

i have a problem in certain company in germany. They use proxy in their network and my program cant communicate with server.
IE works with this settings:
It means:
Automatically detect settings
This is the code:
public static bool CompleteValidation(string regKey)
{
string uri = "***";
int c = 1;
if (Counter < 5) c = 6 - Counter;
string response = "";
try
{
System.Net.ServicePointManager.Expect100Continue = false;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.AllowWriteStreamBuffering = true;
request.Method = "POST";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "pl,en-us;q=0.7,en;q=0.3");
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-2,utf-8;q=0.7,*;q=0.7");
request.KeepAlive = true;
//proxy settings
string exepath = Path.GetDirectoryName(Application.ExecutablePath);
string proxySettings = exepath + #"\proxy.ini";
WebProxy wp = new WebProxy();
if (File.Exists(proxySettings)) {
request.Proxy = WebRequest.DefaultWebProxy;
IniFile ini = new IniFile(proxySettings);
string user = ini.IniReadValue("Proxy", "User");
string pass = ini.IniReadValue("Proxy", "Password");
string domain = ini.IniReadValue("Proxy", "Domain");
string ip = ini.IniReadValue("Proxy", "IP");
string port_s = ini.IniReadValue("Proxy", "Port");
int port = 0;
if (!string.IsNullOrEmpty(ip))
{
if (!string.IsNullOrEmpty(port_s))
{
try
{
port = Convert.ToInt32(port_s);
}
catch (Exception e)
{
ErrorLog.AddToLog("Problem with conversion of port:");
ErrorLog.AddToLog(e.Message);
ErrorLog.ShowLogWindow();
}
wp = new WebProxy(ip, port);
} else {
wp = new WebProxy(ip);
}
}
if (string.IsNullOrEmpty(domain))
wp.Credentials = new NetworkCredential(user, pass);
else
wp.Credentials = new NetworkCredential(user, pass, domain);
request.Proxy = wp;
}
string post = "***";
request.ContentLength = post.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = null;
try
{
writer = new StreamWriter(request.GetRequestStream()); // Here is the WebException thrown
writer.Write(post);
writer.Close();
}
catch (Exception e)
{
ErrorLog.AddToLog("Problem with request sending:");
ErrorLog.AddToLog(e.Message);
ErrorLog.ShowLogWindow();
}
HttpWebResponse Response = null;
try
{
Response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
ErrorLog.AddToLog("Problem with response:");
ErrorLog.AddToLog(e.Message);
ErrorLog.ShowLogWindow();
}
//Request.Proxy = WebProxy.GetDefaultProxy();
//Request.Proxy.Credentials = CredentialCache.DefaultCredentials;
string sResponseHeader = Response.ContentEncoding; // get response header
if (!string.IsNullOrEmpty(sResponseHeader))
{
if (sResponseHeader.ToLower().Contains("gzip"))
{
byte[] b = DecompressGzip(Response.GetResponseStream());
response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b);
}
else if (sResponseHeader.ToLower().Contains("deflate"))
{
byte[] b = DecompressDeflate(Response.GetResponseStream());
response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b);
}
}
// uncompressed, standard response
else
{
StreamReader ResponseReader = new StreamReader(Response.GetResponseStream());
response = ResponseReader.ReadToEnd();
ResponseReader.Close();
}
}
catch (Exception e)
{
ErrorLog.AddToLog("Problem with comunication:");
ErrorLog.AddToLog(e.Message);
ErrorLog.ShowLogWindow();
}
if (response == "***")
{
SaveKeyFiles();
WriteRegKey(regKey);
RenewCounter();
return true;
}
else
{
return false;
}
}
My program logs it as:
[09:13:18] Searching for hardware ID
[09:13:56] Problem with response:
[09:13:56] The remote server returned an error: (407) Proxy Authentication Required.
[09:15:04] problem with comunication:
[09:15:04] Object reference not set to an object instance.
If they write user and pass into proxy.ini file, program works. But the problem is they cant do that. And somehow IE works without it. Is there any way to get those settings from IE or system?
Use GetSystemWebProxy to return what the system default proxy is.
WebRequest.DefaultProxy = WebRequest.GetSystemWebProxy();
But every HttpWebRequest should automatically be filled out with this information by default. For example, the following snippet in a standalone console application should print the correct information on a system with a PAC file configured.
HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
// Obtain the 'Proxy' of the Default browser.
IWebProxy proxy = myWebRequest.Proxy;
// Print the Proxy Url to the console.
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri));
}
else
{
Console.WriteLine("Proxy is null; no proxy will be used");
}
Use DefaultNetworkCredentials to return system proxy credentials.
request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

Dir exists or not on FTP

How do I check if some DIR exists on the server or not?
Although I can check file exists or not through:
try
{
FtpWebRequest request=null;
request = (FtpWebRequest)WebRequest.Create("ftp://" + webrequestUrl + "/somefile.txt");
request.Credentials = new NetworkCredential(username, password);
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
// Okay.
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
//task
}
}
}
But how do I check DIR? If I only specify DIR in URI then it doesn't go to catch if DIR doesn't exists.
request = (FtpWebRequest)WebRequest.Create("ftp://" + webrequestUrl); //no file name
request.Credentials = new NetworkCredential(username, password);
myFtpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
And check if your file/dir is listed.
You need to interrogate the response, it should contain a list of possible files and directorys.
You should not be using a catch to handle program flow.
MSDN example
I don't think the code does what you think it does.
As far as I understand the docs you're trying to get a ls (think dir in DOS/Windows, a list of files in a directory) for a file. That doesn't make sense. It works, somewhat, because you get the exception for trying to access a directory "somefile.txt".
You should be able to do it the right way (tm) by looking at the output of the ListDirectory response of the parent:
Do a ListDirectory ftp://yourserver/ and check if
your file
your directory
is listed.
I use:
private bool CreateFTPDirectory(string directory)
{
try
{
//create the directory
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpURI+"/"+directory));
requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
requestDir.UsePassive = true;
requestDir.UseBinary = true;
requestDir.KeepAlive = false;
//requestDir.UseDefaultCredentials = true;
requestDir.Credentials = new NetworkCredential(UserId, Password);
requestDir.Proxy = WebRequest.DefaultWebProxy;
requestDir.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
return true;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if ((response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) || (((int)response.StatusCode)==521))
{
response.Close();
return true;
}
else
{
response.Close();
return false;
}
}
}
This has the side effect of creating the directory as well. If it already exists you get a 521 result returned which isn't defined in the .NET Enum.
When you connect to an FTP server you might specify the Uri as "ftp//ftp.domain.com/somedirectory" but this translates to: "ftp://ftp.domain.com/homedirectoryforftp/somedirectory". To be able to define the full root directory use "ftp://ftp.domain.com//somedirectory" which translates to //somedirectory on the machine.
By using edtFTPnet
private void ftp_folder_IsExists()
{
FTPClient ftp = default(FTPClient);
ftp = new FTPClient("ftp_host_name_here"); // ex.:- no need to use ftp in the host name, provide name only
ftp.Login("username", "password");
string[] file_and_folders = ftp.Dir(".", false);// . is used to get all the [files and folders] in the root of FTP
string[] file_and_folders_1 = ftp.Dir("MyFolder", false);// this will get all the [files and folder] inside MyFolder (ex. ftp.ahostname.com/MyFolder/)
//checking for a FILE
if (file_and_folders.Contains("something.txt")) {
//Do what you want..
} else {
//Do what you want..
}
//checking for a FOLDER
if (file_and_folders.Contains("A_Folder")) {
//Do what you want..
} else {
//Do what you want..
}
}
Note : Code Written In VB.NET and Converted Using http://converter.telerik.com/

Categories

Resources