using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
namespace IOB_UT_NEXT
{
///
/// Accesso in lettura e scrittura al filesystem per gestione files upload e download
///
public class fileMover
{
#region Protected Fields
///
/// path di lavoro dei metodi leggi/scrivi
///
protected string _workPath;
#endregion Protected Fields
#region Public Fields
///
/// versione statica (singleton) del'oggetto fileMover
///
public static fileMover obj = new fileMover();
///
/// oggetto WebClient
///
public WebClient WebCli;
#endregion Public Fields
#region Public Constructors
///
/// inizializza il metodo alla cartella indicata
///
///
/// non serve +... x retrocompatibilità...
public fileMover(string _path, string _log)
{
setDirs(_path);
WebCli = new WebClient();
}
///
/// metodo di avvio empty
///
public fileMover()
{
WebCli = new WebClient();
}
#endregion Public Constructors
#region Private Methods
///
/// cerca di caricare la directoryInfo o da httpcontext-application re-position o direttamente come workpath
///
///
private DirectoryInfo getDirectoryInfo()
{
DirectoryInfo _di;
_di = new DirectoryInfo(_workPath);
return _di;
}
///
/// Recupera oggetto DirInfo da path
///
///
///
private DirectoryInfo getDirectoryInfo(string path)
{
DirectoryInfo _di = new DirectoryInfo(path);
return _di;
}
///
/// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile
///
/// path completo file
///
private FileInfo getFileInfoByName(string _fullPath)
{
FileInfo _fi;
_fi = new FileInfo(_fullPath);
return _fi;
}
///
/// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile
///
/// cartella file
/// nome file
///
private FileInfo getFileInfoByName(string _path, string _nomeFile)
{
FileInfo _fi;
_fi = new FileInfo(_path + "\\" + _nomeFile);
return _fi;
}
///
/// setta le directory
///
///
private void setDirs(string _path)
{
_workPath = _path;
}
#endregion Private Methods
#region Protected Methods
///
/// converte un byte[] in una string
///
///
///
protected string byteToStr(byte[] _array)
{
System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding();
return encod.GetString(_array);
}
///
/// converte una string in un byte[]
///
///
///
protected byte[] strToByte(string _val)
{
System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding();
return encod.GetBytes(_val);
}
///
/// verifica esistenza directory ed eventualmente crea restituendo nome completo di "/" finale
///
///
///
protected string verDir(string _path)
{
DirectoryInfo di = getDirectoryInfo(_path);
if (!di.Exists)
{
di.Create();
}
if (!_path.EndsWith("/") && !_path.EndsWith(@"\"))
{
_path += "/";
}
return _path;
}
#endregion Protected Methods
#region Public Methods
///
/// elimina il file indicato
///
///
///
public static bool deleteFile(string PathOfFile2Delete)
{
bool ret = true;
try
{
if (File.Exists(PathOfFile2Delete))
{
File.Delete(PathOfFile2Delete);
}
}
catch
{
ret = false;
}
return ret;
}
///
/// esegue un comando in shell
///
///
///
///
///
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;
}
///
/// folder dell'eseguibile corrente
///
///
public static string GetExecutingDirectoryName()
{
var location = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
return new FileInfo(location.AbsolutePath).Directory.FullName;
}
///
/// esegue un comando in shell
///
///
///
///
///
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();
}
///
/// 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.
///
/// Lo stream da cui leggere
/// Lunghezza buffer iniziale (-1 = default 32k)
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;
}
///
/// scompatta tutto il contenuto di un file zip
///
///
///
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;
}
///
/// scompatta uno specifico file contenuto in un file zip
///
/// The input path of zip file.
/// The file2unzip.
///
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;
}
///
/// verifica esistenza directory, eventualmente crea e restituisce controllo DirectoryInfo
///
///
public DirectoryInfo checkDir()
{
DirectoryInfo _di = getDirectoryInfo();
if (!_di.Exists)
{
_di.Create();
}
return _di;
}
///
/// copia il file da From a To...
///
///
///
///
///
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;
}
///
/// copia il file da From a To...
///
///
///
///
///
///
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;
}
///
/// elimina il file + vecchio
///
///
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
{ }
}
///
/// Elimina i file + vecchi di maxNumDays giorni
///
///
public void deleteOlderThan(int maxNumDays)
{
DirectoryInfo _di = checkDir();
FileInfo[] _fis = _di.GetFiles();
DateTime dateLimit = DateTime.Now.AddDays(-maxNumDays);
try
{
_fis.Where(x => x.LastWriteTime x.Delete());
}
catch(Exception exc)
{
Logging.Instance.Error($"Eccezione in deleteOlderThan{Environment.NewLine}{exc}");
}
}
///
/// elenco dei files come array di oggetti FileInfo
///
///
public FileInfo[] elencoFiles_FI()
{
DirectoryInfo _di = checkDir();
return _di.GetFiles();
}
///
/// elenco dei files come array di oggetti FileInfo filtrati per parametro
///
///
///
public FileInfo[] elencoFiles_FI(string _param)
{
DirectoryInfo _di = checkDir();
return _di.GetFiles(_param);
}
///
/// elimina la directory di lavoro se è dir virtuale mappata
///
///
public bool eliminaDir()
{
DirectoryInfo _di = checkDir();
bool fatto = false;
try
{
_di.Delete(true);
fatto = true;
}
catch
{
}
return fatto;
}
///
/// elimina il file indicato dalla directory di lavoro
///
///
///
public bool eliminaFile(string _nomeFile)
{
FileInfo _fi = getFileInfoByName(_nomeFile);
bool fatto = false;
try
{
_fi.Delete();
fatto = true;
}
catch
{
}
return fatto;
}
///
/// elimina il file indicato dalla directory di lavoro
///
/// The _fi.
///
public bool eliminaFile(FileInfo _fi)
{
bool fatto = false;
try
{
_fi.Delete();
fatto = true;
}
catch
{
}
return fatto;
}
///
/// verifica se il file indicato esista in workDir
///
///
///
public bool fileExist(string _nomeFile)
{
bool answ = false;
FileInfo _fi = getFileInfoByName(_nomeFile);
answ = _fi.Exists;
return answ;
}
///
/// verifica se il file indicato esista in _path
///
///
///
///
public bool fileExist(string _path, string _nomeFile)
{
bool answ = false;
FileInfo _fi = getFileInfoByName(_path, _nomeFile);
answ = _fi.Exists;
return answ;
}
///
/// sposta il file da From a To...
///
///
///
///
///
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;
}
///
/// Legge il file indicato in workDir
///
///
///
public string readFile(string _nomeFile)
{
string answ = "";
FileInfo _fi = getFileInfoByName(_nomeFile);
if (_fi.Exists)
{
answ = File.ReadAllText(_fi.FullName);
}
return answ;
}
///
/// scrive il file dallo stream byte[] inviato (SOVRASCRIVENDO!)
///
///
///
///
///
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;
}
///
/// scrive il file dallo stream byte[] inviato
///
///
///
///
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;
}
///
/// scrive il file dalla stringa inviata
///
///
///
///
///
public bool salvaFileString(string _path, string _nomeFile, string _fileString)
{
return salvaFileBuffer(_path, _nomeFile, strToByte(_fileString));
}
///
/// scrive il file dalla stringa inviata
///
///
///
///
public bool salvaFileString(string _nomeFile, string _fileString)
{
return salvaFileBuffer(_nomeFile, strToByte(_fileString));
}
///
/// restituisce lo stream del file richiesto
///
///
///
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;
}
}
///
/// Scarica un file dall'url fornito nella directory indicata x il filemover col nome richiesto
///
/// url del file
/// nome con cui salvare il file
///
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));
}
///
/// restituisce la stringa letta dal file richiesto
///
///
///
public string scaricaFileString(string _nomeFile)
{
return byteToStr(scaricaFile(_nomeFile));
}
///
/// imposta la dir di lavoro
///
///
public void setDirectory(string _path)
{
setDirs(_path);
}
///
/// imposta la dir di lavoro
///
///
/// non serve +... x retrocompatibilità...
public void setDirectory(string _path, string _log)
{
setDirs(_path);
}
///
/// elimina tutti i files con la regexp indicata da una directory, true se cancellato almeno uno
///
/// regexp selezione files in dir (* = tutti!!!)
///
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;
}
///
/// calcola la dim della directory corrente...
///
///
public float totalMb()
{
DirectoryInfo _di = checkDir();
FileInfo[] _fis = _di.GetFiles();
float _byte = 0;
foreach (FileInfo _file in _fis)
{
_byte += _file.Length;
}
return _byte / 1000000;
}
///
/// comprime zip i files corrispondenti alla RegExp indicata nella dir corrente
///
/// Espressione ricerca, come *.txt
/// Nome del file zip da creare
///
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;
}
///
/// comprime zip il file indicato
///
///
///
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;
}
///
/// comprime zip il file indicato
///
/// File in formato FileInfo
///
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 Public Methods
}
}