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);
Related
I have created a process in C# that is intended to move files around by FTP. One part is working - my GetFileFTP. I can retrieve a file from the FTP server and place a copy on my local machine. I also want to copy a file to an archive folder on the FTP server and then delete the original file on the FTP server. I created the functions CopyFileFTP and DeleteFileFTP shown below. They run without error, but the file does not get copied or deleted. I also check the StatusCode in the delete function and everything looks happy. Do you know why this isn't working? Could it be that I only have read-only permission on the server? Would it throw an error if I try to delete and don't have permission or would it just process the command with no action? My supervisor doesn't seem to want to ask the supplier who owns the FTP server if we have the necessary permissions, so I will try posting this question.
public static bool CopyFileFTP(string sFileURI1, string sFileURI2, string sUserName, string sPassword)
{
bool bSuccess = false;
try
{
FtpWebRequest oRequest1 = (FtpWebRequest)WebRequest.Create(sFileURI1);
oRequest1.Credentials = new NetworkCredential(sUserName, sPassword);
oRequest1.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse oResponse = (FtpWebResponse)oRequest1.GetResponse();
Stream oStream1 = oResponse.GetResponseStream();
MemoryStream oMemoryStream = new MemoryStream();
byte[] aChunk = new byte[4096];
int iBytesRead = 0;
do
{
iBytesRead = oStream1.Read(aChunk, 0, aChunk.Length);
if (iBytesRead > 0)
{
oMemoryStream.Write(aChunk, 0, iBytesRead);
}
else
{
break;
}
} while (iBytesRead > 0);
byte[] aBuffer = oMemoryStream.ToArray();
FtpWebRequest oRequest2 = (FtpWebRequest)WebRequest.Create(sFileURI2);
oRequest2.Credentials = new NetworkCredential(sUserName, sPassword);
oRequest2.Method = WebRequestMethods.Ftp.UploadFile;
Stream oStream2 = oRequest2.GetRequestStream();
oStream2.Write(aBuffer, 0, aBuffer.Length);
oStream2.Close();
oStream2.Dispose();
oStream1.Close();
oStream1.Dispose();
bSuccess = true;
}
catch (Exception oException)
{
LogEvent(oException.Message);
}
return bSuccess;
}
public static bool DeleteFileFTP(string sFileURI, string sUserName, string sPassword)
{
bool bSuccess = false;
try
{
FtpWebRequest oRequest = (FtpWebRequest)WebRequest.Create(sFileURI);
oRequest.Credentials = new NetworkCredential(sUserName, sPassword);
oRequest.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse oResponse = (FtpWebResponse)oRequest.GetResponse();
string sWelcomeMessage = oResponse.WelcomeMessage;
string sStatusDescription = oResponse.StatusDescription;
bool bIsMutuallyAuthenticated = oResponse.IsMutuallyAuthenticated;
string sBannerMessage = oResponse.BannerMessage;
FtpStatusCode eStatusCode = oResponse.StatusCode;
string sExitMessage = oResponse.ExitMessage;
oResponse.Close();
bSuccess = true;
}
catch (Exception oException)
{
LogEvent(oException.Message);
}
return bSuccess;
}
It looks fine to me; the code is almost exactly as MSDN documents FtpWebRequest.
I would agree that it is credentials most likely.
Incidentally, have you tried using a traditional FTP client with the same credentials and see if you can perform these actions manually?
Additionally, it appears as you suspected that there is no exception thrown for not having permissions; you can catch an exception but that will mostly be from actual connection errors. You need to process the response's status to find out what the FTP server is telling you.
I need to get the file size so i can later calculate and report to progressBar the download size how much have been downloaded so far and how much still left to download.
In form1 i have a backgroundworker and this is how i'm sending the files to the class with the download method:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < numberOfFiles.Count; i++)
{
int fn = numberOfFiles[i].IndexOf(txtHost.Text, 0);
string fn1 = numberOfFiles[i].Substring(txtHost.Text.Length + 1, numberOfFiles[i].Length - (txtHost.Text.Length + 1));
string dirs = Path.GetDirectoryName(fn1);
string filename = Path.GetFileName(fn1);
ftpProgress1.DownloadFtpContent(sender,numberOfFiles[i], dirs, filename);
}
}
Then in the method DownloadFtpContent i did:
public void DownloadFtpContent(object sender ,string file, string filesdirectories,string fn)
{
try
{
BackgroundWorker bw = sender as BackgroundWorker;
string filenameonly = Path.GetFileName(file);
string ftpdirectories = Path.Combine(ftpcontentdir, filesdirectories);
string fileurl = "ftp://" + file;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(fileurl);
reqFTP.Credentials = new NetworkCredential(UserName, Password);
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.KeepAlive = true;
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse resp = (FtpWebResponse)reqFTP.GetResponse();
Int64 FileContLen = resp.ContentLength;
I see in the fileurl the directory and file name for example:
ftp://ftp.newsxpressmedia.com/Images/CB 967x330.jpg
But using breakpoint on the line:
FtpWebResponse resp = (FtpWebResponse)reqFTP.GetResponse();
I'm getting exception:
WebException:
The remote server returned an error: (550) File unavailable (e.g., file not found, no access
First you have to check if the file is Exist or not on the Ftp Server. if the file is Exist than check the permission for File Access. if u don't have access permission of File than you can't get the File size.
I am trying to create a small console application that downloads files from a ftp server through Explicit FTP over TLS. I have create these applications before but i am getting an error with this one. I keep Getting this error:
The Remote Server returned an error: 150 Opening BINARY mode data connection fro "filename" <2000 bytes>.
I cant seem to figure out that to do, can anyone help me?
this is my code:
public void DownloadFiles(string fileName)
{
uri.Scheme = "ftp";
uri.Host = ftpUrl;
uri.Port = 21;
uri.UserName = username;
uri.Password = password;
uri.Path = "out";
try
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri.ToString() + "/" + fileName));
reqFTP.EnableSsl = true;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(username, password);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response;
response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
FileStream writeStream = new FileStream(localFolder + fileName, FileMode.Create);
long length = response.ContentLength;
int bufferSize = 2048;
Byte[] buffer = new Byte[bufferSize];
int readCount = responseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
writeStream.Write(buffer, 0, readCount);
readCount = responseStream.Read(buffer, 0, bufferSize);
}
AppendLogFile(response, "Downloading Files: ", fileName);
writeStream.Close();
responseStream.Close();
response.Close();
reqFTP.Abort();
}
catch (Exception ex)
{
Console.WriteLine("Error in DownloadFileByFileName method!! " + ex.Message);
}
}
thanks!
I could not find the solution for this so i when over to use Chillkat for this application. works fine. But needed to buy a year license.
this is my code:
public void Connect(string fileName)
{
bool success;
success = ftp.UnlockComponent("license");
if (!success)
{
Console.WriteLine(ftp.LastErrorText);
return;
}
ftp.IdleTimeoutMs = 10000;
ftp.AuthTls = true;
ftp.Ssl = false;
ftp.Hostname = ftpUrl;
ftp.Port = 21;
ftp.Username = username;
ftp.Password = password;
ftp.KeepSessionLog = true;
success = ftp.Connect();
if (success != true)
{
Console.WriteLine(ftp.LastErrorText);
return;
}
ftp.ClearControlChannel();
bool sucess = ftp.GetFile("out/" + fileName, localFolder + fileName);
if (!success)
{
Console.WriteLine(ftp.LastErrorText);
AppendErrorLogFile("Error in downloading file", "Download file method", fileName);
return;
}
else
{
AppendLogFile("Download Success", "Download File Method", fileName);
ftp.DeleteRemoteFile("out/" + fileName);
}
}
long length = response.ContentLength;
Is at fault here I believe, if you use this to download a file that already exists, your request will close before you can get a response from the server and throw the 150 error.
I was wondering what is wrong with this code? Im hosting a ftp on 000webhost and i want to upload a image that the user on my program opens from there computer using the openfiledialog feature
The Button to open image:
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);
}
The code to upload it:
try
{
String sourcefilepath = source; // e.g. “d:/test.docx”
String ftpurl = "ftp://www.locu.site90.com/public_html/"; // e.g. ftp://serverip/foldername/foldername
String ftpusername = "********"; // e.g. username
String ftppassword = "********"; // e.g. password
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = 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;
}
}
I keep getting some errrors
"The requested URI is invalid for this FTP command"
and the second error is
"The remote server returned an error: (530) Not logged in .”
Since you are doing an upload. The destination file name is required in the FTP url. It looks like that is what you might of intended to do with the following line:
string ftpfullpath = ftpurl;
Try changing it to:
string ftpfullpath = ftpurl + filename;
For the not logged in error, some hosting companies only allow secure connections. You can try adding the following line to your code:
ftp.EnableSsl = true;
I am using this method, and that is working well:
public static void UpLoadImage(string image, string targeturl)
{
FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://www.website.com/images/" + targeturl);
req.UseBinary = true;
req.Method = WebRequestMethods.Ftp.UploadFile;
req.Credentials = new NetworkCredential("user", "pass");
byte[] fileData = File.ReadAllBytes(image);
req.ContentLength = fileData.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(fileData, 0, fileData.Length);
reqStream.Close();
}
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);
}
}