FTP File Download C # - c#

In my code I want to download a specific File from FTP-Server to my local machine.I am getting an exception like below
System.InvalidCastException: Unable to cast object of type: 'System.Net.HttpWebRequest' to type 'System.Net.FtpWebRequest' at FTPapp.ftpdownload.Download(String remoteFile, String localFile)
My code:
namespace FTPapp
{
public partial class ftpdownload : Form
{
private string Host = null;
private string user = null;
private string pass = null;
private string SSH = null;
private FtpWebRequest ftprequest = null;
private FtpWebResponse ftpresponse = null;
private Stream ftpStream = null;
private int buffersize = 2048;
public ftpdownload()
{
InitializeComponent();
}
public ftpdownload(string hostIP, string username, string password ,string SSHkey)
{
Host = hostIP;
user = username;
pass = password;
SSH = SSHkey;
}
public void Download(string remoteFile, string localFile)
{
try
{
ftprequest = (FtpWebRequest)FtpWebRequest.Create(Host + "/" + remoteFile);
ftprequest.Credentials = new NetworkCredential(user, pass ,SSH);
ftprequest.UseBinary = true;
ftprequest.UsePassive = true;
ftprequest.KeepAlive = true;
ftprequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpresponse = (FtpWebResponse)ftprequest.GetResponse();
ftpStream = ftpresponse.GetResponseStream();
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
byte[] byteBuffer = new byte[buffersize];
`enter code here` int bytesRead = ftpStream.Read(byteBuffer, 0, buffersize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, buffersize);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
localFileStream.Close();
ftpStream.Close();
ftpresponse.Close();
ftprequest= null;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
txtServer.Text = "http://ftpsite.com";
txtUsername.Text = "";
txtPassword.Text = #"";
txtFilename.Text = #"";
txtSSHKey.Text = "";
}
private void BtnDownload_Click(object sender, EventArgs e)
{
ftpdownload ftp = new ftpdownload("http://ftpsite.com" ,"","","");
ftp.Download(#"Remotepath", #"local path");
}
}
}

We cannot be sure that the link is FTP Uri without checking it.
As specified in microsoft documentation, you need to use ftp:// before the hostname, like: ftp://contoso.com/someFile.txt.
So, how to solve your problem?
First of all, you should add ftp:// to your link. After that you may create a Uri object and check whether it's scheme is Uri.UriSchemeFtp. If not, return.

Related

FTP Download File

I am trying to file download from remote machine with FTP in c# but it doesn't work. when i came GetResponse Method with f10, threw the exception. its says:"unable to connect to remote server", it looks like about connection problem but its not.
when i create request in the code ContentType and PreAuthenticate is threw an exception and said:"System.NotSupportedException"
How can i fix this? Any ideas?
Here's the Connection Info for FTP.
private static string host = #"ftp://XXX.XX.XXX.XX/";
private static string user = "XXXXXXXX";
private static string pass = "XXXXXXXX";
private static string localfile = #"E:/Files/Attachment";
private static string remoteFile = #"D:/log/stdlog.6.txt";
And then FTP class
public class FtpServer
{
private string host = null;
private string user = null;
private string pass = null;
private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
private int bufferSize = 2048;
/* Construct Object */
public FtpServer(string hostIP, string userName, string password) { host = hostIP; user = userName; pass = password; }
public void Download(string remoteFile, string localFile)
{
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host+remoteFile);
ftpRequest.Credentials = new NetworkCredential(user,pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return;
}
}
Unable to connect to remote server could be several reasons.
1) you could be mistakenly typing the server address and pointing to a non-existing address.
2) The server is temporarily shut or down and you cannot access it.
3) You typed in wrong credentials for the server.
Either way, I suggest you to implement using statement in your code rather then using close() on every stream:
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
using (ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
{
using (ftpStream = ftpResponse.GetResponseStream())
{
using (FileStream localFileStream = new FileStream(localFile, FileMode.Create))
{
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
ftpRequest = null;

ftp upload/download in c# for windows mobile 6.5 with opencf.net.ftp

I tried to make an ftp upload and download but it is going all time to Nullreference error. It can be that the opennetcf.net.ftp is not the best way to solve the problem? Can anyone help me to solve the problem?
namespace ftp_load
{
public partial class Form1 : Form
{
public class FTPManagerClass
{
private static string password = "";
private static string username = "";
private static string host = "";
private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
// private int bufferSize = 2048;
public FTPManagerClass(string user, string pass, string hostname)
{
username = user;
password = pass;
host = hostname;
}
public void DownloadFile(string remoteFile, string localFIle)
{
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
ftpRequest.Credentials = new NetworkCredential(username, password);
//ftpRequest.UseBinary = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
FileStream fs = new FileStream(localFIle, FileMode.OpenOrCreate);
fs.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void UploadFile(string localFile, string remoteFile)
{
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
ftpRequest.Credentials = new NetworkCredential(username, password);
// ftpRequest.UseBinary = true;
// ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = false;
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpStream = ftpRequest.GetRequestStream();
FileStream lfs = new FileStream(localFile, FileMode.Open);
byte[] bytebuffer = new byte[lfs.Length];
int bytesSend = lfs.Read(bytebuffer, 0, (int)lfs.Length);
try
{
while (bytesSend != -1)
{
ftpStream.Write(bytebuffer, 0, bytesSend);
bytesSend = lfs.Read(bytebuffer, 0, (int)lfs.Length);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
ftpResponse.Close();
ftpStream.Close();
lfs.Close();
ftpRequest = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
FTPManagerClass client;
private static string password = "";
private static string username = "";
private static string host = "";
private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
public Form1()
{
InitializeComponent();
connMgr = new ConnMgr();
connMgr.StatusChanged += new ConnMgr.StatusChangedEventHandler(StatusChanged_Handler);
}
private ConnMgr connMgr;
private void button1_Click(object sender, EventArgs e)
{
if (txt_br_down.Text != "")
{
client.DownloadFile(#"/GP_FTP/ans.txt", #"/download");
client = new FTPManagerClass("usr", "pwd", "ftp://ftp.tzf.com");
}
else
{
MessageBox.Show("Ures mezo");
}
}
private void txt_br_dw_1_TextChanged(object sender, EventArgs e)
{
}
The GPRS connection builds up, but after the ftp connection has some problem:
private void btn_login_Click(object sender, EventArgs e)
{
}
private void btn_login_Click_1(object sender, EventArgs e)
{
if (!connMgr.Connected)
{
connMgr.Connect("pannon", ConnMgr.ConnectionMode.Synchronous, " ", " ", "net");
txtLog.Text += "Sync connection successful\r\n";
}
else
{
MessageBox.Show("No connection!");
}
}
private void txtLog_TextChanged(object sender, EventArgs e)
{
}
private void StatusChanged_Handler(object sender, ConnMgr.StatusChangedEventArgs e)
{
connMgr.Timeout = 3000;
txtLog.Text += e.desc + "\r\n"; // Show current state's description
if (!connMgr.Waiting)
if (connMgr.Connected)
txtLog.Text += "Confirmed - We are now connected\r\n";
else
{
txtLog.Text += "Confirmed - Connection instance has been released\r\n";
// btnCancel.Enabled = false;
// btnConnect.Enabled = true;
}
if (e.connstatus == ConnMgr.ConnectionStatus.ExclusiveConflict)
MessageBox.Show("If using Activesync, check connection settings for 'Allow wireless connection ...' or remove from homebase.");
}
private void Form1_Load(object sender, EventArgs e)
{
}
No it looks the authentication is ok.There is no problem!
I made this:
try
{
client = new FTPManagerClass("usr", "pwd", "ftp://ftp.tzf.com");
}
catch (Exception ex)
{
MessageBox.Show("Login"+ ex);
}
This is ok!
But after this: ctacke
try
{
MessageBox.Show("before download");
client.DownloadFile("/GP_FTP/ans.txt", "/download");
MessageBox.Show("after download");
}
catch (Exception ex1)
{
MessageBox.Show("file"+ ex1);
}
The problem is now : In client.DownloadFile System.nullreferenceException
Now i have no idea :(.
it can be some pity thing...
Why this is null? client.DownloadFile(#"/GP_FTP/ans.txt", #"/download");
i tried client.DownloadFile("/GP_FTP/ans.txt", "/download"); and client.DownloadFile("ans.txt", "/download");
and the same. WHY?
This won't work:
client.DownloadFile(#"/GP_FTP/ans.txt", #"/download");
client = new FTPManagerClass("usr", "pwd", "ftp://ftp.tzf.com");
You can't perform operations on a variable if you have not assigned something to it yet - then you get a NullReferenceException. The new bit goes first:
client = new FTPManagerClass("usr", "pwd", "ftp://ftp.tzf.com");
client.DownloadFile(#"/GP_FTP/ans.txt", #"/download");
Specifying the ftp address and sending the username, password before trying to download the file should make more sense, too.

FTP Upload image error

I am trying to upload images to my ftp server hosted by a web hosting to store users profile images for when they close and re open my application
Note If there is any other way I can store it please suggest it
I have tryed the following code below but I keep receiving a error saying
An unhandled exception of type 'System.Net.WebException' occurred in App.exe Additional information: The remote server returned an error: (500) Syntax error, command unrecognized
A comment a person said to me was "That error is quite generic. It could mean you have a firewall or something blocking something or it can mean that SSL is not supported on the server" Could any of you help towards this comment. Because I don't understand how i can block the firewall or stop it or excreter excreter (Not that important help if you can)
Carrying on to the main problem ... My code - (FTP Part) In a public static class
public static void UpLoadImage(string source)
{
try
{
String sourcefilepath = source;
String ftpurl = "ftp://www.locu.site90.com/public_html/";
String ftpusername = "a4670620";
String ftppassword = "********";
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl + filename;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = false;
ftp.EnableSsl = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
And here is where I call the void when selecting a image
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == DialogResult.OK)
{
Bitmap bit = new Bitmap(open.FileName);
pictureBox1.Image = bit;
pictureBox2.Image = bit;
bit.Dispose();
string fullPath = open.FileName;
string fileName = open.SafeFileName;
string path = fullPath.Replace(fileName, "");
User.Details.UpLoadImage(fullPath);
}
}
Any help given is 100% appreciated from me myself!
I am using the following code to create the path:
System.Net.FtpWebRequest ftpReq = null;
System.Net.FtpWebResponse ftpRes = null;
try
{
ftpReq = System.Net.WebRequest.Create(path) as System.Net.FtpWebRequest;
ftpReq.Credentials = new System.Net.NetworkCredential(user, password);
ftpReq.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory;
ftpReq.KeepAlive = false;
ftpRes = ftpReq.GetResponse() as System.Net.FtpWebResponse;
ftpRes.Close();
}
catch (WebException we)
{
//do something with the error
}
catch (Exception e)
{
//do something with the error
}
and to upload the file why you don't use
public byte[] UploadFile(string address, string fileName):
Code for uploading to ftp:
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(tabFolder.FldUser, tabFolder.FldPassword);
wc.UploadFile(folder.TrimEnd(#"\".ToCharArray()) + #"\" + fn, jpgFile);

webclient.UploadData "The underlying Connection was Closed: An unexpected error occured on a recieve"

I am trying to upload image and video using code below, there is no issue with image upload using ftp, but when I am uploading video I get the following error
Error
The underlying connection was closed: An unexpected error occurred on a receive.
Following is the code I am using to upload
Code
try
{
string uploadFileName = Path.GetFileName(FU_Video.FileName);
uploadFileName = "video." + uploadFileName.Split('.')[1];
using (WebClient client = new WebClient())
{
string ftpAddres = "ftp://username:pasword#url-path" + fullname;
if (!GetAllFilesList(ftpAddres, "username", "password"))
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpAddres);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
}
client.UploadData(new Uri(ftpAddres + "/" + uploadFileName), FU_Video.FileBytes);
}
and here is the stack trace.
stack Trace
at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
at System.Net.WebClient.UploadData(Uri address, String method, Byte[] data)
at System.Net.WebClient.UploadData(Uri address, Byte[] data)
at MentorMentee.SignUp.signup.btn_VidPreview_Click(Object sender, EventArgs e) in I:\VS Projects\code\MentorMentee1\MentorMentee\SignUp\signup.aspx.cs:line 469
after searching I read to make connection alive false, but I am getting error on line client.UploadData(uri,byte[]);
please let me know what is wrong with my code? as video is uploaded on ftp, but I get error.
I remember having similar issue, but don't remember exactly what made it work. Here is the code that works well for me:
public void Upload(Stream stream, string fileName)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
try
{
FtpWebRequest ftpRequest = CreateFtpRequest(fileName);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream requestSream = ftpRequest.GetRequestStream())
{
Pump(stream, requestSream);
}
var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
}
catch (Exception e)
{
throw new FtpException(
string.Format("Failed to upload object. fileName: {0}, stream: {1}", fileName, stream), e);
}
}
private FtpWebRequest CreateFtpRequest(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
string serverUri = string.Format("{0}{1}", ftpRoot, fileName);
var ftpRequest = (FtpWebRequest)WebRequest.Create(serverUri);
ftpRequest.Credentials = new NetworkCredential(configuration.UserName, configuration.Password);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = false;
return ftpRequest;
}
private static void Pump(Stream input, Stream output)
{
var buffer = new byte[2048];
while (true)
{
int bytesRead = input.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
output.Write(buffer, 0, bytesRead);
}
}

C# Doesn't get file size on FTP Server

When I want to get the size of a file on my ftp server I gets nothing.
Anyone see a problem in the code?
it seems to me that method is good
the class :
public string getFileSize(string fileName)
{
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
StreamReader ftpReader = new StreamReader(ftpStream);
string fileInfo = null;
try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
return fileInfo;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return "";
}
the process :
ftp ftpClientCheckFile = new ftp(#"ftp://******.******.fr", "***********", "********");
string ftpfileSize = ftpClientCheckFile.getFileSize(fileName);
if (ftpfileSize == localfilesize)
{
this.Invoke(new Action(() => { MessageBox.Show(this, "*********", "***", MessageBoxButtons.OK, MessageBoxIcon.Information); }));
ftpClientCheckFile = null;
}
else
{
this.Invoke(new Action(() => { MessageBox.Show(this, "***** ", "*******", MessageBoxButtons.OK, MessageBoxIcon.Information); }));
}
Thanks for help.
You need to use the ContentLength property to get the file size
Console.WriteLine(ftpResponse.ContentLength.ToString());
Some ftp servers don't support getfilesize so you will have to use ListDirectoryDetails

Categories

Resources