using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;

namespace IOB_UT
{
    /// <summary>
    /// Accesso in lettura e scrittura al filesystem per gestione files upload e download
    /// </summary>
    public class fileMover
    {
        #region oggetti private

        /// <summary>
        /// path di lavoro dei metodi leggi/scrivi
        /// </summary>
        protected string _workPath;

        /// <summary>
        /// oggetto WebClient
        /// </summary>
        public WebClient WebCli;

        /// <summary>
        /// setta le directory
        /// </summary>
        /// <param name="_path"></param>
        private void setDirs(string _path)
        {
            _workPath = _path;
        }

        /// <summary>
        /// verifica esistenza directory ed eventualmente crea restituendo nome completo di "/" finale
        /// </summary>
        /// <param name="_path"></param>
        /// <returns></returns>
        protected string verDir(string _path)
        {
            DirectoryInfo di = getDirectoryInfo(_path);
            if (!di.Exists)
            {
                di.Create();
            }
            if (!_path.EndsWith("/") && !_path.EndsWith(@"\"))
            {
                _path += "/";
            }
            return _path;
        }

        #endregion oggetti private

        #region inizializzazione

        /// <summary>
        /// inizializza il metodo alla cartella indicata
        /// </summary>
        /// <param name="_path"></param>
        /// <param name="_log">non serve +... x retrocompatibilità...</param>
        public fileMover(string _path, string _log)
        {
            setDirs(_path);
            WebCli = new WebClient();
        }

        /// <summary>
        /// metodo di avvio empty
        /// </summary>
        public fileMover()
        {
            WebCli = new WebClient();
        }

        #endregion inizializzazione

        #region Public Fields

        /// <summary>
        /// versione statica (singleton) del'oggetto fileMover
        /// </summary>
        public static fileMover obj = new fileMover();

        #endregion Public Fields

        #region Private Methods

        /// <summary>
        /// cerca di caricare la directoryInfo o da httpcontext-application re-position o direttamente come workpath
        /// </summary>
        /// <returns></returns>
        private DirectoryInfo getDirectoryInfo()
        {
            DirectoryInfo _di;
            _di = new DirectoryInfo(_workPath);
            return _di;
        }

        /// <summary>
        /// Recupera oggetto DirInfo da path
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private DirectoryInfo getDirectoryInfo(string path)
        {
            DirectoryInfo _di = new DirectoryInfo(path);
            return _di;
        }

        /// <summary>
        /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile
        /// </summary>
        /// <param name="_fullPath">path completo file</param>
        /// <returns></returns>
        private FileInfo getFileInfoByName(string _fullPath)
        {
            FileInfo _fi;
            _fi = new FileInfo(_fullPath);
            return _fi;
        }

        /// <summary>
        /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile
        /// </summary>
        /// <param name="_path">cartella file</param>
        /// <param name="_nomeFile">nome file</param>
        /// <returns></returns>
        private FileInfo getFileInfoByName(string _path, string _nomeFile)
        {
            FileInfo _fi;
            _fi = new FileInfo(_path + "\\" + _nomeFile);
            return _fi;
        }

        #endregion Private Methods

        #region oggetti public

        /// <summary>
        /// converte un byte[] in una string
        /// </summary>
        /// <param name="_array"></param>
        /// <returns></returns>
        protected string byteToStr(byte[] _array)
        {
            System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding();
            return encod.GetString(_array);
        }

        /// <summary>
        /// converte una string in un byte[]
        /// </summary>
        /// <param name="_val"></param>
        /// <returns></returns>
        protected byte[] strToByte(string _val)
        {
            System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding();
            return encod.GetBytes(_val);
        }

        /// <summary>
        /// elimina il file indicato
        /// </summary>
        /// <param name="PathOfFile2Delete"></param>
        /// <returns></returns>
        public static bool deleteFile(string PathOfFile2Delete)
        {
            bool ret = true;
            try
            {
                if (File.Exists(PathOfFile2Delete))
                {
                    File.Delete(PathOfFile2Delete);
                }
            }
            catch
            {
                ret = false;
            }
            return ret;
        }

        /// <summary>
        /// esegue un comando in shell
        /// </summary>
        /// <param name="workDir"></param>
        /// <param name="Command"></param>
        /// <param name="Timeout"></param>
        /// <returns></returns>
        public static int ExecuteCommand(string workDir, string Command, int Timeout)
        {
            int ExitCode;
            ProcessStartInfo ProcessInfo;
            Process Process;

            ProcessInfo = new ProcessStartInfo(Command);
            ProcessInfo.CreateNoWindow = false;
            ProcessInfo.UseShellExecute = true;
            ProcessInfo.WorkingDirectory = workDir;
            //ProcessInfo.RedirectStandardError = true;
            //ProcessInfo.RedirectStandardInput = true;
            //ProcessInfo.RedirectStandardOutput = true;
            Process = Process.Start(ProcessInfo);
            Process.WaitForExit(Timeout);
            ExitCode = Process.ExitCode;
            Process.Close();

            return ExitCode;
        }

        /// <summary>
        /// folder dell'eseguibile corrente
        /// </summary>
        /// <returns></returns>
        public static string GetExecutingDirectoryName()
        {
            var location = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
            return new FileInfo(location.AbsolutePath).Directory.FullName;
        }

        /// <summary>
        /// esegue un comando in shell
        /// </summary>
        /// <param name="workDir"></param>
        /// <param name="Command"></param>
        /// <param name="Timeout"></param>
        /// <returns></returns>
        public static void LaunchCommand(string workDir, string Command, int Timeout)
        {
            //int ExitCode;
            ProcessStartInfo ProcessInfo;
            Process Process;

            ProcessInfo = new ProcessStartInfo(Command);
            ProcessInfo.CreateNoWindow = false;
            ProcessInfo.UseShellExecute = true;
            ProcessInfo.WorkingDirectory = workDir;
            //ProcessInfo.RedirectStandardError = true;
            //ProcessInfo.RedirectStandardInput = true;
            //ProcessInfo.RedirectStandardOutput = true;
            Process = Process.Start(ProcessInfo);
            //Process.WaitForExit(Timeout);
            //ExitCode = Process.ExitCode;
            //Process.Close();
        }

        /// <summary>
        /// Legge i dati da uno stream fino a quando arriva alla fine.
        /// I dati sono restituiti come un byte[] array. un eccezione IOException è
        /// sollevata se una delle chiamate IO sottostanti fallisce.
        /// </summary>
        /// <param name="stream">Lo stream da cui leggere</param>
        /// <param name="initialLength">Lunghezza buffer iniziale (-1 = default 32k)</param>
        public static byte[] ReadFully(Stream stream, int initialLength)
        {
            // If we've been passed an unhelpful initial length, just
            // use 32K.
            if (initialLength < 1)
            {
                initialLength = 32768;
            }

            byte[] buffer = new byte[initialLength];
            int read = 0;

            int chunk;
            while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
            {
                read += chunk;

                // If we've reached the end of our buffer, check to see if there's
                // any more information
                if (read == buffer.Length)
                {
                    int nextByte = stream.ReadByte();

                    // End of stream? If so, we're done
                    if (nextByte == -1)
                    {
                        return buffer;
                    }

                    // Nope. Resize the buffer, put in the byte we've just
                    // read, and continue
                    byte[] newBuffer = new byte[buffer.Length * 2];
                    Array.Copy(buffer, newBuffer, buffer.Length);
                    newBuffer[read] = (byte)nextByte;
                    buffer = newBuffer;
                    read++;
                }
            }
            // Buffer is now too big. Shrink it.
            byte[] ret = new byte[read];
            Array.Copy(buffer, ret, read);
            return ret;
        }

        /// <summary>
        /// scompatta tutto il contenuto di un file zip
        /// </summary>
        /// <param name="InputPathOfZipFile"></param>
        /// <returns></returns>
        public static bool UnZipFile(string InputPathOfZipFile)
        {
            bool ret = true;
            try
            {
                if (File.Exists(InputPathOfZipFile))
                {
                    string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile);

                    using (ZipInputStream ZipStream = new

          ZipInputStream(File.OpenRead(InputPathOfZipFile)))
                    {
                        ZipEntry theEntry;
                        while ((theEntry = ZipStream.GetNextEntry()) != null)
                        {
                            if (theEntry.IsFile)
                            {
                                if (theEntry.Name != "")
                                {
                                    string strNewFile = @"" + baseDirectory + @"\" + theEntry.Name;
                                    if (File.Exists(strNewFile))
                                    {
                                        continue;
                                    }

                                    using (FileStream streamWriter = File.Create(strNewFile))
                                    {
                                        int size = 4096;
                                        byte[] data = new byte[4096];
                                        while (true)
                                        {
                                            size = ZipStream.Read(data, 0, data.Length);
                                            if (size > 0)
                                            {
                                                streamWriter.Write(data, 0, size);
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }
                                        streamWriter.Close();
                                    }
                                }
                            }
                            else if (theEntry.IsDirectory)
                            {
                                string strNewDirectory = @"" + baseDirectory + @"\" + theEntry.Name;
                                if (!Directory.Exists(strNewDirectory))
                                {
                                    Directory.CreateDirectory(strNewDirectory);
                                }
                            }
                        }
                        ZipStream.Close();
                    }
                }
            }
            catch
            {
                ret = false;
            }
            return ret;
        }

        /// <summary>
        /// scompatta uno specifico file contenuto in un file zip
        /// </summary>
        /// <param name="InputPathOfZipFile">The input path of zip file.</param>
        /// <param name="file2unzip">The file2unzip.</param>
        /// <returns></returns>
        public static bool UnZipSingleFile(string InputPathOfZipFile, string file2unzip)
        {
            bool ret = true;
            try
            {
                if (File.Exists(InputPathOfZipFile))
                {
                    string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile);

                    using (ZipInputStream ZipStream = new ZipInputStream(File.OpenRead(InputPathOfZipFile)))
                    {
                        ZipEntry theEntry;
                        while ((theEntry = ZipStream.GetNextEntry()) != null)
                        {
                            if (theEntry.IsFile)
                            {
                                if (theEntry.Name == file2unzip)
                                {
                                    string strNewFile = @"" + baseDirectory + @"\" + theEntry.Name;
                                    if (File.Exists(strNewFile))
                                    {
                                        continue;
                                    }

                                    using (FileStream streamWriter = File.Create(strNewFile))
                                    {
                                        int size = 4096;
                                        byte[] data = new byte[4096];
                                        while (true)
                                        {
                                            size = ZipStream.Read(data, 0, data.Length);
                                            if (size > 0)
                                            {
                                                streamWriter.Write(data, 0, size);
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }
                                        streamWriter.Close();
                                    }
                                }
                            }
                            else if (theEntry.IsDirectory)
                            {
                                string strNewDirectory = @"" + baseDirectory + @"\" +

                theEntry.Name;
                                if (!Directory.Exists(strNewDirectory))
                                {
                                    Directory.CreateDirectory(strNewDirectory);
                                }
                            }
                        }
                        ZipStream.Close();
                    }
                }
            }
            catch
            {
                ret = false;
            }
            return ret;
        }

        /// <summary>
        /// verifica esistenza directory, eventualmente crea e restituisce controllo DirectoryInfo
        /// </summary>
        /// <returns></returns>
        public DirectoryInfo checkDir()
        {
            DirectoryInfo _di = getDirectoryInfo();
            if (!_di.Exists)
            {
                _di.Create();
            }
            return _di;
        }

        /// <summary>
        /// copia il file da From a To...
        /// </summary>
        /// <param name="_pathFrom"></param>
        /// <param name="_pathTo"></param>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFile)
        {
            bool fatto = false;
            // verifica directory
            _pathFrom = verDir(_pathFrom);
            _pathTo = verDir(_pathTo);
            FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile);
            try
            {
                _fi.CopyTo(_pathTo + _nomeFile, true);
                fatto = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
            return fatto;
        }

        /// <summary>
        /// copia il file da From a To...
        /// </summary>
        /// <param name="_pathFrom"></param>
        /// <param name="_pathTo"></param>
        /// <param name="_nomeFileOrig"></param>
        /// <param name="_nomeFileDest"></param>
        /// <returns></returns>
        public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFileOrig, string _nomeFileDest)
        {
            bool fatto = false;
            // verifica directory
            _pathFrom = verDir(_pathFrom);
            _pathTo = verDir(_pathTo);
            FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFileOrig);
            try
            {
                _fi.CopyTo(_pathTo + _nomeFileDest, true);
                fatto = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
            return fatto;
        }

        /// <summary>
        /// elimina il file + vecchio
        /// </summary>
        /// <returns></returns>
        public void deleteOldest()
        {
            DirectoryInfo _di = checkDir();
            FileInfo[] _fis = _di.GetFiles();
            DateTime _oldest = DateTime.Now;
            string _nome = "";
            try
            {
                FileInfo _currFI = _fis[0];
                foreach (FileInfo _file in _fis)
                {
                    if (_file.LastWriteTime < _oldest)
                    {
                        _nome = _file.Name;
                        _oldest = _file.LastWriteTime;
                        _currFI = _file;
                    }
                }
                //eliminaFile(_nome);
                eliminaFile(_currFI);
            }
            catch
            { }
        }

        /// <summary>
        /// elenco dei files come array di oggetti FileInfo
        /// </summary>
        /// <returns></returns>
        public FileInfo[] elencoFiles_FI()
        {
            DirectoryInfo _di = checkDir();
            return _di.GetFiles();
        }

        /// <summary>
        /// elenco dei files come array di oggetti FileInfo filtrati per parametro
        /// </summary>
        /// <param name="_param"></param>
        /// <returns></returns>
        public FileInfo[] elencoFiles_FI(string _param)
        {
            DirectoryInfo _di = checkDir();
            return _di.GetFiles(_param);
        }

        /// <summary>
        /// elimina la directory di lavoro se è dir virtuale mappata
        /// </summary>
        /// <returns></returns>
        public bool eliminaDir()
        {
            DirectoryInfo _di = checkDir();
            bool fatto = false;
            try
            {
                _di.Delete(true);
                fatto = true;
            }
            catch
            {
            }
            return fatto;
        }

        /// <summary>
        /// elimina il file indicato dalla directory di lavoro
        /// </summary>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public bool eliminaFile(string _nomeFile)
        {
            FileInfo _fi = getFileInfoByName(_nomeFile);
            bool fatto = false;
            try
            {
                _fi.Delete();
                fatto = true;
            }
            catch
            {
            }
            return fatto;
        }

        /// <summary>
        /// elimina il file indicato dalla directory di lavoro
        /// </summary>
        /// <param name="_fi">The _fi.</param>
        /// <returns></returns>
        public bool eliminaFile(FileInfo _fi)
        {
            bool fatto = false;
            try
            {
                _fi.Delete();
                fatto = true;
            }
            catch
            {
            }
            return fatto;
        }

        /// <summary>
        /// verifica se il file indicato esista in workDir
        /// </summary>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public bool fileExist(string _nomeFile)
        {
            bool answ = false;
            FileInfo _fi = getFileInfoByName(_nomeFile);
            answ = _fi.Exists;
            return answ;
        }

        /// <summary>
        /// verifica se il file indicato esista in _path
        /// </summary>
        /// <param name="_path"></param>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public bool fileExist(string _path, string _nomeFile)
        {
            bool answ = false;
            FileInfo _fi = getFileInfoByName(_path, _nomeFile);
            answ = _fi.Exists;
            return answ;
        }

        /// <summary>
        /// sposta il file da From a To...
        /// </summary>
        /// <param name="_pathFrom"></param>
        /// <param name="_pathTo"></param>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public bool muoviFile(string _pathFrom, string _pathTo, string _nomeFile)
        {
            bool fatto = false;
            // verifica directory
            _pathTo = verDir(_pathTo);
            _pathFrom = verDir(_pathFrom);
            FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile);
            try
            {
                _fi.CopyTo(_pathTo + _nomeFile, true);
                _fi.Delete();
                fatto = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
            return fatto;
        }

        /// <summary>
        /// Legge il file indicato in workDir
        /// </summary>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public string readFile(string _nomeFile)
        {
            string answ = "";
            FileInfo _fi = getFileInfoByName(_nomeFile);
            if (_fi.Exists)
            {
                answ = File.ReadAllText(_fi.FullName);
            }
            return answ;
        }

        /// <summary>
        /// scrive il file dallo stream byte[] inviato (SOVRASCRIVENDO!)
        /// </summary>
        /// <param name="_path"></param>
        /// <param name="_nomeFile"></param>
        /// <param name="_fileBuffer"></param>
        /// <returns></returns>
        public bool salvaFileBuffer(string _path, string _nomeFile, byte[] _fileBuffer)
        {
            _workPath = _path;
            DirectoryInfo _di = getDirectoryInfo(_path);
            if (!_di.Exists)
            {
                _di.Create();
            }
            FileInfo _fi = getFileInfoByName(_path, _nomeFile);
            Stream _stream;
            // se esiste cancello
            if (_fi.Exists)
            {
                _fi.Delete();
            }
            // quindi creao
            _stream = _fi.Create();
            _stream.Write(_fileBuffer, 0, _fileBuffer.Length);
            _stream.Flush();
            _stream.Close();

            return true;
        }

        /// <summary>
        /// scrive il file dallo stream byte[] inviato
        /// </summary>
        /// <param name="_nomeFile"></param>
        /// <param name="_fileBuffer"></param>
        /// <returns></returns>
        public bool salvaFileBuffer(string _nomeFile, byte[] _fileBuffer)
        {
            DirectoryInfo _di = getDirectoryInfo();
            if (!_di.Exists)
            {
                _di.Create();
            }
            FileInfo _fi = getFileInfoByName(_nomeFile);
            Stream _stream;
            if (!_fi.Exists)
            {
                _stream = _fi.Create();
            }
            else
            {
                _stream = _fi.OpenWrite();
            }
            _stream.Write(_fileBuffer, 0, _fileBuffer.Length);
            _stream.Flush();
            _stream.Close();

            return true;
        }

        /// <summary>
        /// scrive il file dalla stringa inviata
        /// </summary>
        /// <param name="_path"></param>
        /// <param name="_nomeFile"></param>
        /// <param name="_fileString"></param>
        /// <returns></returns>
        public bool salvaFileString(string _path, string _nomeFile, string _fileString)
        {
            return salvaFileBuffer(_path, _nomeFile, strToByte(_fileString));
        }

        /// <summary>
        /// scrive il file dalla stringa inviata
        /// </summary>
        /// <param name="_nomeFile"></param>
        /// <param name="_fileString"></param>
        /// <returns></returns>
        public bool salvaFileString(string _nomeFile, string _fileString)
        {
            return salvaFileBuffer(_nomeFile, strToByte(_fileString));
        }

        /// <summary>
        /// restituisce lo stream del file richiesto
        /// </summary>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public byte[] scaricaFile(string _nomeFile)
        {
            FileInfo _fi = getFileInfoByName(_nomeFile);
            // verifica ci siano attach...
            if (_fi.Exists)
            {
                Stream _stream = _fi.OpenRead();
                byte[] _risposta = ReadFully(_stream, -1);
                _stream.Close();
                return _risposta;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Scarica un file dall'url fornito nella directory indicata x il filemover col nome richiesto
        /// </summary>
        /// <param name="urlFile">url del file</param>
        /// <param name="nomeDest">nome con cui salvare il file</param>
        /// <returns></returns>
        public void scaricaFileFromWeb(string urlFile, string nomeDest)
        {
            // utilizzo l'oggetto webCli...

            WebCli.Credentials = System.Net.CredentialCache.DefaultCredentials;
            WebCli.DownloadFile(urlFile, string.Format("{0}\\{1}", _workPath, nomeDest));
        }

        /// <summary>
        /// restituisce la stringa letta dal file richiesto
        /// </summary>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public string scaricaFileString(string _nomeFile)
        {
            return byteToStr(scaricaFile(_nomeFile));
        }

        /// <summary>
        /// imposta la dir di lavoro
        /// </summary>
        /// <param name="_path"></param>
        public void setDirectory(string _path)
        {
            setDirs(_path);
        }

        /// <summary>
        /// imposta la dir di lavoro
        /// </summary>
        /// <param name="_path"></param>
        /// <param name="_log">non serve +... x retrocompatibilità...</param>
        public void setDirectory(string _path, string _log)
        {
            setDirs(_path);
        }

        /// <summary>
        /// elimina tutti i files con la regexp indicata da una directory, true se cancellato almeno uno
        /// </summary>
        /// <param name="nomeCercato">regexp selezione files in dir (* = tutti!!!)</param>
        /// <returns></returns>
        public bool svuotaDir(string nomeCercato)
        {
            bool answ = false;
            FileInfo[] _fis = elencoFiles_FI(nomeCercato);
            foreach (FileInfo _file in _fis)
            {
                eliminaFile(_file.Name);
                answ = true;
            }
            return answ;
        }

        /// <summary>
        /// calcola la dim della directory corrente...
        /// </summary>
        /// <returns></returns>
        public float totalMb()
        {
            DirectoryInfo _di = checkDir();
            FileInfo[] _fis = _di.GetFiles();
            float _byte = 0;
            foreach (FileInfo _file in _fis)
            {
                _byte += _file.Length;
            }
            return _byte / 1000000;
        }

        /// <summary>
        /// comprime zip i files corrispondenti alla RegExp indicata nella dir corrente
        /// </summary>
        /// <param name="regExp">Espressione ricerca, come *.txt</param>
        /// <param name="outZipFileName">Nome del file zip da creare</param>
        /// <returns></returns>
        public bool zippaFilesByRegExp(string regExp, string outZipFileName)
        {
            bool fatto = false;
            // inizializzo il file zip...
            DirectoryInfo _di = checkDir();
            // calcolo il nome del file zip...
            string nomeZip = string.Format("{0}/{1}.zip", _di.FullName, outZipFileName.Replace(".zip", ""));
            // inizio a inserire dati
            try
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip)))
                {
                    s.SetLevel(5);
                    byte[] buffer = new byte[4096];
                    // effettuo una ricerca dei files corrispondenti al criterio regexp, e per ognuno effettuo inserimento in zipfile...
                    FileInfo[] filesTrovati = elencoFiles_FI(regExp);
                    ZipEntry entry;
                    foreach (FileInfo _fi in filesTrovati)
                    {
                        // calcolo la nuova entry nel file zip...
                        entry = new ZipEntry(Path.GetFileName(_fi.FullName));
                        // Could also use the last write time or similar for the file.
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(_fi.FullName))
                        {
                            // Using a fixed size buffer here makes no noticeable difference for output but keeps a lid on memory usage.
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
                fatto = true;
            }
            catch
            { }
            return fatto;
        }

        /// <summary>
        /// comprime zip il file indicato
        /// </summary>
        /// <param name="_nomeFile"></param>
        /// <returns></returns>
        public bool zippaSingoloFile(string _nomeFile)
        {
            bool fatto = false;
            FileInfo _fi = getFileInfoByName(_nomeFile);
            // calcolo il nome del file zip...
            string nomeZip = string.Format("{0}.zip", _fi.FullName);
            try
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip)))
                {
                    s.SetLevel(5);
                    byte[] buffer = new byte[4096];
                    ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName));
                    // Could also use the last write time or similar for the file.
                    entry.DateTime = DateTime.Now;
                    s.PutNextEntry(entry);
                    using (FileStream fs = File.OpenRead(_fi.FullName))
                    {
                        // Using a fixed size buffer here makes no noticeable difference for output
                        // but keeps a lid on memory usage.
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            s.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                    s.Finish();
                    s.Close();
                }
                fatto = true;
            }
            catch
            { }
            return fatto;
        }

        /// <summary>
        /// comprime zip il file indicato
        /// </summary>
        /// <param name="_fi">File in formato FileInfo</param>
        /// <returns></returns>
        public bool zippaSingoloFile(FileInfo _fi)
        {
            bool fatto = false;
            // calcolo il nome del file zip...
            string nomeZip = string.Format("{0}.zip", _fi.FullName);
            try
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip)))
                {
                    s.SetLevel(5);
                    byte[] buffer = new byte[4096];
                    ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName));
                    // Could also use the last write time or similar for the file.
                    entry.DateTime = DateTime.Now;
                    s.PutNextEntry(entry);
                    using (FileStream fs = File.OpenRead(_fi.FullName))
                    {
                        // Using a fixed size buffer here makes no noticeable difference for output
                        // but keeps a lid on memory usage.
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            s.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                    s.Finish();
                    s.Close();
                }
                fatto = true;
            }
            catch
            { }
            return fatto;
        }

        #endregion oggetti public
    }
}