I'm having some trouble with uploading a file to a FTP server from C#. My code works well on localhost, but on the live environment it keeps giving me a The operation has timed out. exception.
I use the following code:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath + "/orders.csv");
request.UsePassive = true;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = -1;
StreamReader sourceStream = new StreamReader(context.Server.MapPath("~/App_Data/orders.csv"));
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
Where ftpPath is the URL of my FTP server: ftp://myserver.com
Does anyone know what I'm doing wrong here? :-)
Thanks in advance.
Some time we need to download, upload file from FTP server. Here is some example to FTP operation.
For this we need to include one namespace and it is. using System.Net
public void DownloadFile(string HostURL, string UserName, string Password, string SourceDirectory, string FileName, string LocalDirectory)
{
if (!File.Exists(LocalDirectory + FileName))
{
try
{
FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(HostURL + "/" + SourceDirectory + "/" + FileName);
requestFileDownload.Credentials = new NetworkCredential(UserName, Password);
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
Stream responseStream = responseFileDownload.GetResponseStream();
FileStream writeStream = new FileStream(LocalDirectory + FileName, FileMode.Create);
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
responseStream.Close();
writeStream.Close();
requestFileDownload = null;
responseFileDownload = null;
}
catch (Exception ex)
{
throw ex;
}
}
}
This was a permission issue. Seems like the FTP user on my webhotel was restricted (somehow) Tried with another FTP with a user with full permissions and it worked.
Related
Here is a function I have written to download a file from the FTP server. This works when I call this on the Desktop application or console application. But fails and gives the error message when this is in Windows Service or make a console application called from windows scheduler. I need to get a selected files daily. I am trying to automate instead of running manually every day morning.
private void GetFile(string url, string user, string pwd, string folder, string filename
, string destloc, string destfile)
{
try
{
string RemoteFtpPath = url + folder + "/" + filename;
String DestLoc = destloc + destfile;
String Username = user;
String Password = pwd;
Boolean UseBinary = false; // use true for .zip file or false for a text file
Boolean UsePassive = false;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(RemoteFtpPath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.KeepAlive = true;
request.UsePassive = UsePassive;
request.UseBinary = UseBinary;
request.Credentials = new NetworkCredential(Username, Password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
if (File.Exists(DestLoc))
File.Delete(DestLoc);
using (FileStream writer = new FileStream(DestLoc, FileMode.Create))
{
long length = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[2048];
readCount = responseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
writer.Write(buffer, 0, readCount);
readCount = responseStream.Read(buffer, 0, bufferSize);
}
}
reader.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
}
By changing the properties solved the issue.
request.KeepAlive = false;
request.UsePassive = true;
request.UseBinary = false;
can't upload file to ftp this is my code....
string filename = Path.GetFileName(source);
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftp + ftpFolder + filename);
request.Credentials = new NetworkCredential("username", "password");
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Proxy = new WebProxy();
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = request.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
File.Delete(source);
always an error is occuring at GetRequestStream() the command is not recognized... how can I overcome this error ?
Any help will be appreciated....
add these two line
request.KeepAlive = false;
request.UsePassive= false;
then also if it is not working check whether your antivirus is blocking FTP
Here's some problem with transporting .csv file to FTP server. Before transfering it's okay, but when i'm checking it on FTP it looks like broken or something:
"ЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ T8пїЅпїЅпїЅпїЅпїЅпїЅ\p3>#L #E8?5=:> BпїЅaпїЅ="
Is it problem with encoding? I'm using this method of download:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://xxxxxxxx.xx/" + name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = true;
request.UseBinary = true;
request.Credentials = new NetworkCredential("xxxx", "qweqwe123");
StreamReader sourceStream = new StreamReader("F:\\" + xxxx);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
Don't like to answer under my aquestions, but it's too long for comment:
Solved, maybe somebody have this problem. Try to use this upload method:
FileInfo toUpload = new FileInfo("log.txt");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://csharpcoderr.com/public_html/" + toUpload.Name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("name", "pass");
Stream ftpStream = request.GetRequestStream();
FileStream fileStream = File.OpenRead("log.txt");
byte[] buffer = new byte[1024];
int bytesRead = 0;
do
{
bytesRead = fileStream.Read(buffer, 0, 1024);
ftpStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
fileStream.Close();
ftpStream.Close();
I can across this question with the same issue.
Expanding on Brawl_Ups solution...
And it seems that its best to use the BinaryReader for binary files.
This is a snippet I eventfully came up with...
This is a current work in progress and any edits are welcome.
public string UploadFile()
{
string sRetVal = string.Empty;
string sFullDestination = this.DestinatinFullIDPath + this.UpLoadFileName;
try
{
if ((this.CreateDestinationDir(this.DestinatinFullModulePath) == true) &
(this.CreateDestinationDir(this.DestinatinFullIDPath) == true))
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(sFullDestination);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(this.UserName, this.Password);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.EnableSsl = false;
byte[] fileContents;
using (BinaryReader binReader = new BinaryReader(File.OpenRead(this.UpLoadFullName)))
{
FileInfo fi = new FileInfo(this.UpLoadFullName);
binReader.BaseStream.Position = 0;
fileContents = binReader.ReadBytes((int)fi.Length);
}
ftpRequest.ContentLength = fileContents.Length;
using (Stream requestStream = ftpRequest.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse())
{
sRetVal = string.Format("Upload File Complete, status {0}", response.StatusDescription);
}
}
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
return sRetVal;
}
I need to upload text file from local machine to ftp server using c#.
I've tried folowing code but it did't work.
private bool UploadFile(FileInfo fileInfo)
{
FtpWebRequest request = null;
try
{
string ftpPath = "ftp://www.tt.com/" + fileInfo.Name
request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.Credentials = new NetworkCredential("ftptest", "ftptest");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = false;
request.Timeout = 60000; // 1 minute time out
request.ServicePoint.ConnectionLimit = 15;
byte[] buffer = new byte[1024];
using (FileStream fs = new FileStream(fileInfo.FullPath, FileMode.Open))
{
int dataLength = (int)fs.Length;
int bytesRead = 0;
int bytesDownloaded = 0;
using (Stream requestStream = request.GetRequestStream())
{
while (bytesRead < dataLength)
{
bytesDownloaded = fs.Read(buffer, 0, buffer.Length);
bytesRead = bytesRead + bytesDownloaded;
requestStream.Write(buffer, 0, bytesDownloaded);
}
requestStream.Close();
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
request = null;
}
return false;
}// UploadFile
any suggestions ???
You need to actually send the request by calling GetResponse().
You can also make your code much simpler by calling fs.CopyTo(requestStream).
I tinkered around with a bit ftp code and got the following, which seems to work pretty well for me.
ftpUploadloc is a ftp://ftp.yourftpsite.com/uploaddir/yourfilename.txt
ftpUsername and ftpPassword should be self explanatory.
Finally currentLog is the location of the file you're uploading.
Let me know how this worked out for you, if anyone else has any other suggestions I welcome those.
private void ftplogdump()
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUploadloc);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
StreamReader sourceStream = new StreamReader(currentLog);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
// Remove before publishing
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
I'm making a FTP client and trying to upload file to server (~300 MB), but I get following error when nearly 100 MB of the file were transfered:
The underlying connection was closed: An unexpected error occurred on a receive.
Here's my code:
private void UploadFile(string filepath, string filename)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://" + server + "/" + filename);
//ftp.KeepAlive = false;
//ftp.Timeout = 1000000;
//ftp.UsePassive = true;
//ftp.ReadWriteTimeout = 100000;
Path.GetFileName(filepath);
ftp.Credentials = new NetworkCredential(username, password);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream stream = File.OpenRead(filepath);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
Stream requestStream = ftp.GetRequestStream();
//requestStream.ReadTimeout = 1000000;
//requestStream.WriteTimeout = 1000000;
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception ex) { CreateRunLogFile(ex.Message); }
CreateRunLogFile("Uploading of file " + filepath + " ended.");
}
I try to use,
ftp.KeepAlive = false;
ftp.Timeout = 1000000;
ftp.UsePassive = true;
But it didn't help.
Check the destination firewall settings. If it is a LINUX server running vsFTPd then the server ftp service has FILESIZE and TIMEOUT settings in the config file.
Be sure to restart vsFTPd service after FILESIZE and TIMEOUT settings are adjusted.