Can't upload file to ftp in c# - c#

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

Related

Access denied on client.DownloadFile() [duplicate]

I am using .NET 4 C#. I am trying to upload and then download a ZIP file to (my) server.
For uploading I have
using (WebClient client = new WebClient())
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(MyUrl);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.EnableSsl = false;
request.Credentials = new NetworkCredential(MyLogin, MyPassword);
byte[] fileContents = null;
using (StreamReader sourceStream = new StreamReader(LocalFilePath))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
FtpWebResponse response = null;
response = (FtpWebResponse)request.GetResponse();
response.Close();
}
This seems to work, in that I get a file on the server of the right size.
1) How do I stream it, rather than load it into memory first? I will be uploading very large files.
And for downloading I have
using (WebClient client = new WebClient())
{
string HtmlResult = String.Empty;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteFile);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.EnableSsl = false;
request.Credentials = new NetworkCredential(MyLogin, MyPassword);
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
using (FileStream writer = new FileStream(localFilename, 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);
}
}
}
2) Everything seems to work ... except when I try to unzip the downloaded ZIP file I get an invalid ZIP file.
Upload
The most trivial way to upload a binary file to an FTP server using .NET framework is using WebClient.UploadFile:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile(
"ftp://ftp.example.com/remote/path/file.zip", #"C:\local\path\file.zip");
If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, transfer resuming, etc), use FtpWebRequest. Easy way is to just copy a FileStream to FTP stream using Stream.CopyTo:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream fileStream = File.OpenRead(#"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
}
If you need to monitor an upload progress, you have to copy the contents by chunks yourself:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream fileStream = File.OpenRead(#"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
byte[] buffer = new byte[10240];
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, read);
Console.WriteLine("Uploaded {0} bytes", fileStream.Position);
}
}
For GUI progress (WinForms ProgressBar), see:
How can we show progress bar for upload with FtpWebRequest
If you want to upload all files from a folder, see
Recursive upload to FTP server in C#.
Download
The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
"ftp://ftp.example.com/remote/path/file.zip", #"C:\local\path\file.zip");
If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, resuming transfers, etc), use FtpWebRequest. Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(#"C:\local\path\file.zip"))
{
ftpStream.CopyTo(fileStream);
}
If you need to monitor a download progress, you have to copy the contents by chunks yourself:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(#"C:\local\path\file.zip"))
{
byte[] buffer = new byte[10240];
int read;
while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, read);
Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
}
}
For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar
If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

C# download large file from FTP get hung

I have a FTP (Filezila server), and I would like to download a large file on it, using c#.
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(userName, password);
client.DownloadFile(new Uri("ftp://XXX.XXX.XXX.XXX/" + fileName), destinationFileFullPath);
or
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://XXX.XXX.XXX.XXX/" + fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.KeepAlive = true; // I tried both
request.UseBinary = true; // I tried both
request.UsePassive = true;
request.Credentials = new NetworkCredential(userName, password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// Writing bytes to local files
using (var outputStream = File.OpenWrite(destinationFileFullPath))
{
byte[] chunk = new byte[2048];
int bytesRead;
do
{
bytesRead = responseStream.Read(chunk, 0, chunk.Length);
outputStream.Write(chunk, 0, bytesRead);
} while (bytesRead > 0);
outputStream.Flush();
}
responseStream.Close();
response.Close();
For small file, it works well, but for large file (by large I mean around ~300MB and more) it works, but at the end of the transfer (I see on filezilla server side that the transfer is a success) for an unknown reason my app just hang on the line
client.DownloadFile(new Uri("ftp://XXX.XXX.XXX.XXX/" + fileName), destinationFileFullPath);
or
bytesRead = responseStream.Read(chunk, 0, chunk.Length);
until I got a timeout exception. If I force the break (pause) I can see that is really stuck on this line. It is like if Filezilla close the connection and C# just wait more to read...
Did you already experienced this issue?
Thanks for your help.

File corrupted after upload to FTP server with WebRequest

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

Uploading file to FTP

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.

Uploading multiple files in .NET through FTP

I am thinking of using following code, but I want to transfer hundreds of files and it does not look viable to connect and then disconnect on every file transfer.
request = (FtpWebRequest) FtpWebRequest.Create(FtpAddress + file);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(User, Pass);
request.UsePassive = IsPassive;
request.UseBinary = true;
request.KeepAlive = false;
FileStream fs = File.OpenRead("");
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();
What options do I have for uploading all of these files using a single connection?
I have not verified this to be true, but in my quick 30 second search, if you set
request.KeepAlive = true;
on every request you create except the last one, apparently only the first FTPWebRequest makes a full login connection.
Then when you create the last FTPWebRequest, set
request.KeepAlive = false;
and it will close the connection when done. You can verify this if you have access to the FTP server's logs.

Categories