Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we unzip file in FTP server using C#

Tags:

c#

.net

zip

ftp

Can I extract the ZIP file in FTP and place this extracted file on the same location using C#?

like image 565
Nithin Avatar asked Aug 29 '17 09:08

Nithin


People also ask

Can you unzip in FTP?

It is not possible to unzip files over an FTP connection. FTP stands for "File Transfer Protocol", which was only designed to transfer and partly manage files on the remote end, but not to execute commands.


1 Answers

Download via FTP to MemoryStream, then you can unzip, example shows how to get stream, just change to MemoryStream and unzip. Example doesn't use MemoryStream but if you are familiar with streams it should be trivial to modify these two examples to work for you.

example from: https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-download-files-with-ftp

using System;  
using System.IO;  
using System.Net;  
using System.Text;  

namespace Examples.System.Net  
{  
    public class WebRequestGetExample  
    {  
        public static void Main ()  
        {  
            // Get the object used to communicate with the server.  
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");  
            request.Method = WebRequestMethods.Ftp.DownloadFile;  

            // This example assumes the FTP site uses anonymous logon.  
            request.Credentials = new NetworkCredential ("anonymous","[email protected]");  

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();  

            Stream responseStream = response.GetResponseStream();  
            StreamReader reader = new StreamReader(responseStream);  
            Console.WriteLine(reader.ReadToEnd());  

            Console.WriteLine("Download Complete, status {0}", response.StatusDescription);  

            reader.Close();  
            response.Close();    
        }  
    }  
}

decompress stream, example from: https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }
        }
    }
}

here is a working example of downloading zip file from ftp, decompressing that zip file and then uploading the compressed files back to the same ftp directory

using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string location = @"ftp://localhost";
            byte[] buffer = null;

            using (MemoryStream ms = new MemoryStream())
            {
                FtpWebRequest fwrDownload = (FtpWebRequest)WebRequest.Create($"{location}/test.zip");
                fwrDownload.Method = WebRequestMethods.Ftp.DownloadFile;
                fwrDownload.Credentials = new NetworkCredential("anonymous", "[email protected]");

                using (FtpWebResponse response = (FtpWebResponse)fwrDownload.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    //zipped data stream
                    //https://stackoverflow.com/a/4924357
                    byte[] buf = new byte[1024];
                    int byteCount;
                    do
                    {
                        byteCount = stream.Read(buf, 0, buf.Length);
                        ms.Write(buf, 0, byteCount);
                    } while (byteCount > 0);
                    //ms.Seek(0, SeekOrigin.Begin);
                    buffer = ms.ToArray();
                }
            }

            //include System.IO.Compression AND System.IO.Compression.FileSystem assemblies
            using (MemoryStream ms = new MemoryStream(buffer))
            using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Update))
            {
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    FtpWebRequest fwrUpload = (FtpWebRequest)WebRequest.Create($"{location}/{entry.FullName}");
                    fwrUpload.Method = WebRequestMethods.Ftp.UploadFile;
                    fwrUpload.Credentials = new NetworkCredential("anonymous", "[email protected]");

                    byte[] fileContents = null;
                    using (StreamReader sr = new StreamReader(entry.Open()))
                    {
                        fileContents = Encoding.UTF8.GetBytes(sr.ReadToEnd());
                    }

                    if (fileContents != null)
                    {
                        fwrUpload.ContentLength = fileContents.Length;

                        try
                        {
                            using (Stream requestStream = fwrUpload.GetRequestStream())
                            {
                                requestStream.Write(fileContents, 0, fileContents.Length);
                            }
                        }
                        catch(WebException e)
                        {
                            string status = ((FtpWebResponse)e.Response).StatusDescription;
                        }
                    }
                }
            }
        }
    }
}
like image 121
Aaron. S Avatar answered Sep 23 '22 00:09

Aaron. S