Reputation: 918
I have to download zip file from ftp using c# code. i have used the following code.
Uri url = new Uri("ftp://ftpurl");
if (url.Scheme == Uri.UriSchemeFtp)
{
FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
//Set credentials if required else comment this Credential code
NetworkCredential objCredential = new NetworkCredential(userid, Pwd);
objRequest.Credentials = objCredential;
objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
byte[] buffer = new byte[16 * 1024];
int len = 0;
FileStream objFS = new FileStream(@"E:\ftpwrite", FileMode.Create, FileAccess.Write, FileShare.Read);
while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
{
objFS.Write(buffer, 0, len);
}
objFS.Close();
objResponse.Close();
}
but this code is not giving me the correct response as i want to save file from ftp and this code is writing the data from file in bytes to my file. my file is a zip file not a text file. please help me what should i have to do or i am mistunderstanding.
Upvotes: 0
Views: 1593
Reputation: 3284
If you're not opposed to using free 3rd party libraries, you can use http://www.enterprisedt.com/products/edtftpnet/download.html
It makes accessing the FTP a lot simpler IMO. Sample code (taken and slightly modified from their documentation):
using (FTPConnection ftp = new FTPConnection())
{
ftpConnection.ServerAddress = "myserver";
ftpConnection.UserName = userName;
ftpConnection.Password = password;
ftpConnection.Connect();
ftpConnection.DownloadFile(localFilePath, remoteFileName);
}
Upvotes: 1
Reputation: 1500515
My guess is that it's something to do with the fact that you're using StreamReader
. It's possible that on construction it's reading from the stream to try to determine the encoding. As you're not really using it - just the BaseStream
- it's pointless and leads to unclear code.
Just use:
Stream inputStream = objResponse.GetResponseStream();
Additionally, you should use using
statements for all the streams, and the response.
Oh, and if you're using .NET 4 or higher, use Stream.CopyTo
to save yourself some time.
Upvotes: 1