Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have two files one zip file and other text file but when we are downloading so its getting error:-
when i unzip file so its getting error:-
"Cannot read that as a ZipFile."
I want to download all files from ftp and unzip only zip file.

Error in this line:-
C#
string zipToUnpack = @"C:\" + file;
string unpackDirectory = @"C:\";
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
    foreach (ZipEntry ze in zip1)
    {
        ze.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
    }
}



This code is running successfully with only one zip file.
Only one file is unzipping but more than one are not downloading zip and text file its getting error "Cannot read that as a ZipFile".

Please help me.
Thanks in Advance.

Ankit Agarwal
Software Engineer

What I have tried:

C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] files = ReadFileList();
            FTPSettings.IP = "xxxxxxxx/Test";
            FTPSettings.UserID = "xxxx";
            FTPSettings.Password = "xxxx";
            //FtpWebRequest reqFTP = null;
            //Stream ftpStream = null;
            foreach (string file in files)
            {
                //string fileName = e.Argument.ToString();

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + FTPSettings.IP + "/" + file);
                request.Credentials = new NetworkCredential(FTPSettings.UserID, FTPSettings.Password);
                request.Method = WebRequestMethods.Ftp.GetFileSize;
                request.Proxy = null;

                long fileSize; // this is the key for ReportProgress
                using (WebResponse resp = request.GetResponse())
                    fileSize = resp.ContentLength;

                request = (FtpWebRequest)WebRequest.Create("ftp://" + FTPSettings.IP + "/" + file);
                request.Credentials = new NetworkCredential(FTPSettings.UserID, FTPSettings.Password);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                using (FtpWebResponse responseFileDownload = (FtpWebResponse)request.GetResponse())
                using (Stream responseStream = responseFileDownload.GetResponseStream())
                using (FileStream writeStream = new FileStream(@"C:\" + file, FileMode.Create))
                {

                    int Length = 2048;
                    Byte[] buffer = new Byte[Length];
                    int bytesRead = responseStream.Read(buffer, 0, Length);
                    int bytes = 0;

                    while (bytesRead > 0)
                    {
                        writeStream.Write(buffer, 0, bytesRead);
                        bytesRead = responseStream.Read(buffer, 0, Length);
                        bytes += bytesRead;// don't forget to increment bytesRead !
                        int iProgress = 0;
                        int totalSize = (int)(fileSize) / 1000; // Kbytes
                        if (totalSize > 0)
                        {
                            iProgress = (bytes / 1000) * 100 / totalSize;
                        }
                        backgroundWorker1.ReportProgress(iProgress, totalSize);
                    }
                }
string zipToUnpack = @"C:\" + file;
                string unpackDirectory = @"C:\";
                using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
                {
                    foreach (ZipEntry ze in zip1)
                    {
                        ze.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
                    }
                }
}

public string[] ReadFileList()
        {
            //Debugger.Break();
            string[] mydownloadFiles;
            StringBuilder myresult = new StringBuilder();
            //WebResponse myresponse = null;
            StreamReader myreader = null;
            FtpWebRequest myreqFTP = null;
            try
            {

                FTPSettings.IP = "xxxxxxx/Test";
                FTPSettings.UserID = "xxxx";
                FTPSettings.Password = "xxxx";
                myreqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPSettings.IP + "/"));
                myreqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                myreqFTP.UseBinary = true;

                myreqFTP.Credentials = new NetworkCredential(FTPSettings.UserID, FTPSettings.Password);
                FtpWebResponse response = (FtpWebResponse)myreqFTP.GetResponse();
                myreader = new StreamReader(response.GetResponseStream());
                string myline = myreader.ReadLine();
                while (myline != null)
                {
                    myresult.Append(myline);
                    myresult.Append("\n");
                    myline = myreader.ReadLine();
                }
                // to remove the trailing '\n'
                myresult.Remove(myresult.ToString().LastIndexOf('\n'), 1);
                return myresult.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                if (myreader != null)
                {
                    myreader.Close();
                }
                mydownloadFiles = null;
                return mydownloadFiles;
            }
        }



public static class FTPSettings
        {
            public static string IP { get; set; }
            public static string UserID { get; set; }
            public static string Password { get; set; }
        }
Posted
Updated 6-Sep-16 0:28am
v4
Comments
Philippe Mori 6-Sep-16 13:14pm    
I hope it is not your real code! Never, uses hard-coded path like that.. There are no guaranty that there is a c: drive and that you can write under it.
There are many other poor practices like:
- hard-coded constant (learn a Don't Repeat Yourself - DRY),
- not using Path.Combine to merge path parts,
- using a static class for FTPSettings,
- declaring variables before their first use,
- not using an using statement for some disposable objects when it could have been used,
- not following .NET conventions,
- creating a "long" string to split it afterward (you should have used a list and if necessary convert that to an array at the end as it would be much efficient if the string is somewhat long),
- using Remove and LastIndexOf when you could have used TrimEnd instead (which is self-documenting),
- functions that do more than one things (learn about Single Responsability Principle - SRP),
- poorly named variables,
- discutable indentation,
...

Check the value of your TotalSize variable before using it to divide. I would put it into an if statement
C#
iProgress int = 0;
if(TotalSize > 0 ){iProgress = (bytes / 1000) * 100 / totalSize;}

backgroundWorker1.ReportProgress(iProgress, totalSize);


TotalSize may be 0 because of a type conversion as divide will give a decimal, your () are in the wrong place
 
Share this answer
 
v2
Comments
Agarwal1984 6-Sep-16 4:44am    
Thanks but now second problem is when i unzip file so its getting error:-
Cannot read that as a ZipFile.
I am using this code:-

string zipToUnpack = @"C:\" + file;
string unpackDirectory = @"C:\";
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
foreach (ZipEntry ze in zip1)
{
ze.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
Philippe Mori 6-Sep-16 13:17pm    
Write compilable code. You invert int and iProgress.
Mycroft Holmes 6-Sep-16 18:40pm    
Erk same error as the OP, my only excuse, it was typed into the answer not copied from the IDE.
If you are getting a Divide By Zero exception in this code:
C#
bytes += bytesRead;// don't forget to increment bytesRead !
int totalSize = (int)(fileSize) / 1000; // Kbytes
backgroundWorker1.ReportProgress((bytes / 1000) * 100 / totalSize, totalSize);
Then the problem has to be that totalSize is zero in the final line: which means that the fileSize is less than 1000.

We can't fix that for you: we can't make files bigger! You need to check where you get fileSize from using the debugger and either get a better value into it, or (if it is correct and below 1000) test for it and not do the divide at all.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900