Get confirmation or error after FTP upload - c#

Using the script below, I uploaded a file to a FTP server. It worked, but would be nice if the script would also show a message box with a confirmation if the upload is successful. Or a message box displaying an error code if the upload failed. Any help please?
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://example.com/target.txt", "STOR", localFilePath);
}
I know I should do something like this:
byte[] responseArray = client.UploadFile("ftp://example.com/target.txt", localFilePath);
string s = System.Text.Encoding.ASCII.GetString(responseArray);
I just don't know how to put the pieces toghether.

You could try to use a Try & Catch
https://msdn.microsoft.com/en-us/library/xtd0s8kd(v=vs.110).aspx

Ok, found a good solution to this:
bool exception = false;
try
{
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FtpUser.Text, FtpPass.Text);
client.UploadFile("ftp://example.com/file.txt", "STOR", MyFilePath);
}
}
catch (Exception ex)
{
exception = true;
MessageBox.Show(ex.Message);
}
if(!exception){
MessageBox.Show("Upload worked!");
}

Related

C# The remote server returned an error (401) unauthorized

I am trying to download a xml file from an url but I get this error:
"The remote server returned an error (401) unauthorized". Also, this webpage needs some credentials.
I searched on different topics before coming to ask you, but I didn't find a solution to this...
Here are two versions of codes I tried but didn't work:
try
{
WebClient wClient = new WebClient();
wClient.Credentials = new NetworkCredential(nni, pwd);
var dlString = wClient.DownloadString(url);
//Stream data = wClient.OpenRead(url);
//var reader = new XmlTextReader(wClient.OpenRead(url));
//doc.LoadXml();
doc.Load(wClient.OpenRead(url));
Console.WriteLine(doc.InnerText);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(xmlUrl);
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(nni, pwd);
string htmlCode = client.DownloadString(xmlUrl);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Can you guys please help me on this?

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.

Check if connect to remote server by Webclient

I want to check if my project can connect to the remote server by Webclient in ASP.NET C# and do something.
here is my code
WebClient webClient = new WebClient();
webClient.Credentials = new System.Net.NetworkCredential(username, password);
if (webClient.OpenRead(url83).IsConnected) // Here, i want to check
{
XmlTextReader reader1 = new XmlTextReader(webClient.OpenRead(url83));
reader1.WhitespaceHandling = WhitespaceHandling.None;
//Do something
}
As described here best way to check internet connectivity might be something like
try
{
using (var client = new WebClient())
using (var stream = client.OpenRead(url83))
{
XmlTextReader reader1 = new XmlTextReader(stream);
reader1.WhitespaceHandling = WhitespaceHandling.None;
//Do something
}
}
catch (WebException ex)
{
// occurs when any error occur while reading from network stream
}

upload file to https webserver using c# client

I want to upload a file securely from client machine to a webserver using C# client. It will be helpful to get some sample application of this. Also I want to know how can I achieve this with ssl certificate.
Thanks,
Abdul
WebClient webClient = new WebClient();
string webAddress = null;
try
{
webAddress = #"http://myCompany/ShareDoc/";
webClient.Credentials = CredentialCache.DefaultCredentials;
WebRequest serverRequest = WebRequest.Create(webAddress);
WebResponse serverResponse;
serverResponse = serverRequest.GetResponse();
serverResponse.Close();
webClient.UploadFile(webAddress + logFileName, "PUT", logFileName);
webClient.Dispose();
webClient = null;
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}

How to check FTP connection?

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;
}

Categories

Resources