using ICSharpCode.SharpZipLib.Zip; using NLog; using System; using System.Diagnostics; using System.IO; using System.Net; namespace SteamWare.IO { /// /// Accesso in lettura e scrittura al filesystem per gestione files upload e download /// public class fileMover { #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) { if (Log == null) { Log = LogManager.GetCurrentClassLogger(); } setDirs(_path); WebCli = new WebClient(); } /// /// metodo di avvio empty /// public fileMover() { if (Log == null) { Log = LogManager.GetCurrentClassLogger(); } WebCli = new WebClient(); } #endregion Public Constructors #region Public Methods /// /// Effettua copia files da locale a rete con auth (Local 2 Network)... /// /// /// /// /// /// /// /// public static bool copiaFileL2N(string pathSource, string pathDest, NetworkCredential credentialsDest, string fileSource, string fileDest) { bool fatto = false; Log.Info($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}"); try { using (new NetworkConnection(pathDest, credentialsDest)) { File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); fatto = true; } } catch (Exception exc) { Log.Error($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}"); } return fatto; } /// /// Effettua copia files via rete con auth (Net 2 Net)... /// /// /// /// /// /// /// /// public static bool copiaFileN2N(string pathSource, string pathDest, NetworkCredential credentialsSource, NetworkCredential credentialsDest, string fileSource, string fileDest) { bool fatto = false; Log.Info($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}"); try { using (new NetworkConnection(pathSource, credentialsSource)) using (new NetworkConnection(pathDest, credentialsDest)) { File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); fatto = true; } } catch (Exception exc) { Log.Error($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}"); } return fatto; } /// /// elimina la folder indicata /// /// Path della fodler da eliminare /// Indica se cancellare in modo ricorsivo /// public static bool deleteDir(string PathOfDir2Delete, bool recursive = true) { bool ret = true; try { if (Directory.Exists(PathOfDir2Delete)) { Directory.Delete(PathOfDir2Delete, recursive); } } catch (Exception ex) { ret = false; Log.Error($"Non sono riuscito ad eliminare la directory {PathOfDir2Delete} richiesta: eccezione {ex}"); } return ret; } /// /// elimina il file indicato /// /// /// public static bool deleteFile(string PathOfFile2Delete) { bool ret = true; try { if (File.Exists(PathOfFile2Delete)) { File.Delete(PathOfFile2Delete); } } catch (Exception ex) { ret = false; Log.Error(string.Format("Non sono riuscito ad eliminare file: eccezione {0}", ex)); } return ret; } /// /// Copia il contenuto directory da From a To (opzionalmente in modo ricorsivo)... /// /// Nome dir sorgente /// Nome dir destinazione /// Indica se copiare ricorsivamente /// Indica se sovrascrivere i dati (default = true) /// public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, bool overwrite = true) { // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirName); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } DirectoryInfo[] dirs = dir.GetDirectories(); // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, overwrite); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } /// /// 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; } /// /// restituisce la stringa completa e corretta del filepath del server (anche con vDir) /// /// path relativo alla cartella iis dell'applicativo /// path fisico tradotto public static string getFilePath(string pathRel) { return System.Web.HttpContext.Current.Server.MapPath(pathRel); } /// /// 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 (Exception ex) { ret = false; Log.Error(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex)); } 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 (Exception ex) { ret = false; Log.Error(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex)); } 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(System.Web.HttpContext.Current.Server.MapPath(_pathTo) + _nomeFileDest, true); fatto = true; } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); _fi.CopyTo(_pathTo + _nomeFileDest, true); fatto = true; } return fatto; } /// /// elimina il file + vecchio /// /// public void deleteOldest() { DirectoryInfo _di = checkDir(); FileInfo[] _fis = _di.GetFiles(); DateTime _oldest = DateTime.Now; string _nome = ""; foreach (FileInfo _file in _fis) { if (_file.CreationTime < _oldest) { _nome = _file.Name; } } eliminaFile(_nome); } /// /// ottiene il dataset dei files presenti nella directory indicata all'istanziazione dell'oggetto /// /// public DataLayer_generic.filesDataTable elencoFiles() { DirectoryInfo _di = checkDir(); FileInfo[] _files = _di.GetFiles(); DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); return _dsEF; } /// /// ottiene il dataset dei files DEL TIPO "like {param}" presenti nella directory indicata /// all'istanziazione dell'oggetto /// /// public DataLayer_generic.filesDataTable elencoFiles(string _param) { DirectoryInfo _di = checkDir(); FileInfo[] _files = _di.GetFiles(_param); DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); return _dsEF; } /// /// 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); } /// /// ottiene il dataset dei files presenti nella directory indicata esplicitamente /// /// /// dir da indicizzare... già mappata! ( es SteamwareStrings.getFilePath(...) ) /// /// public DataLayer_generic.filesDataTable elencoFilesDir(string directory) { _workPath = directory; return elencoFiles(); } /// /// elenco sub-directory array di oggetti FileInfo filtrati per parametro /// /// public DirectoryInfo[] elencoSubdir_DI() { DirectoryInfo _di = checkDir(); return _di.GetDirectories(); } /// /// elenco sub-directory array di oggetti FileInfo filtrati per parametro /// /// /// public DirectoryInfo[] elencoSubdir_DI(string _param) { DirectoryInfo _di = checkDir(); return _di.GetDirectories(_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 { } if (fatto) { Log.Info($"Eliminazione file {_nomeFile} eseguita"); } else { Log.Info($"impossibile Eliminare il file {_nomeFile}"); } 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; if (!answ) { // registro che non ho trovaot il file: path e nome file! Log.Info(string.Format("Attenzione: non e' stato possibile trovare il file!{0}wrkDir:{1}{0}file:{2}", Environment.NewLine, _workPath, _nomeFile)); } 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; if (!answ) { // registro che non ho trovaot il file: path e nome file! Log.Info(string.Format("Attenzione: non e' stato possibile trovare il file!{0}path:{1}{0}file:{2}", Environment.NewLine, _path, _nomeFile)); } 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, true); try { _fi.CopyTo(_pathTo + _nomeFile, true); _fi.Delete(); fatto = true; } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } return fatto; } /// /// scrive il file dallo stream byte[] inviato /// /// /// /// /// public bool salvaFileBuffer(string _path, string _nomeFile, byte[] _fileBuffer) { _workPath = _path; DirectoryInfo _di = getDirectoryInfo(_path, true); if (!_di.Exists) { _di.Create(); } FileInfo _fi = getFileInfoByName(_path, _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 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); } /// /// imposta la dir di lavoro impostandola dal mapPath corretto della web app... (come /// subfolder della web app) /// /// public void setDirectoryMapPath(string _path) { setDirs(System.Web.HttpContext.Current.Server.MapPath(_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 (Exception e) { Log.Error(string.Format("Errore in creazione file zip con parametri {0} e {1}: {2}", regExp, outZipFileName, e)); } 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 #region Protected Fields /// /// path di lavoro dei metodi leggi/scrivi /// protected string _workPath; #endregion Protected Fields #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); } /// /// Recupera path correttamente (se fisico o virtuale /// /// /// protected string GetPath(string path) { if (Path.IsPathRooted(path)) { return path; } // altrimenti MapPath! return System.Web.HttpContext.Current.Server.MapPath(path); } /// /// 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, true); if (!di.Exists) { di.Create(); } if (!_path.EndsWith("/") && !_path.EndsWith(@"\")) { _path += "/"; } return _path; } #endregion Protected Methods #region Private Fields private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); #endregion Private Fields #region Private Methods /// /// restituisce una tab di files dato l'elenco dei files /// /// /// private static DataLayer_generic.filesDataTable tabellaFiles(FileInfo[] _files) { DataLayer_generic.filesDataTable _dsEF = new DataLayer_generic.filesDataTable(); DataLayer_generic.filesRow _riga; foreach (FileInfo _fi in _files) { _riga = _dsEF.NewfilesRow(); _riga.dataCreaz = _fi.CreationTime; _riga.dataMod = _fi.LastWriteTime; _riga.Nome = _fi.Name; _riga.size = _fi.Length / 1000; _dsEF.AddfilesRow(_riga); } return _dsEF; } /// /// cerca di caricare la directoryInfo o da httpcontext-application re-position o /// direttamente come workpath /// /// private DirectoryInfo getDirectoryInfo() { DirectoryInfo _di; try { _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath)); } catch { _di = new DirectoryInfo(_workPath); } return _di; } /// /// imposta la directory richiesta... /// /// private DirectoryInfo getDirectoryInfo(string path, bool absPath) { DirectoryInfo _di; if (absPath) { _di = new DirectoryInfo(path); } else { try { _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(path)); } catch { _di = new DirectoryInfo(path); } } return _di; } /// /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente /// come workpath + nomefile /// /// /// private FileInfo getFileInfoByName(string _nomeFile) { FileInfo _fi; try { _fi = new FileInfo(GetPath(_workPath + "\\" + _nomeFile)); } catch (Exception exc) { Log.Error($"Errore in recupero info file: {_nomeFile}{Environment.NewLine}{exc}"); _fi = new FileInfo(_workPath + "\\" + _nomeFile); } return _fi; } /// /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente /// come workpath + nomefile /// /// The _path. /// The _nome file. /// private FileInfo getFileInfoByName(string _path, string _nomeFile) { FileInfo _fi; try { _fi = new FileInfo(GetPath(_path + _nomeFile)); } catch (Exception exc) { Log.Error($"Errore in recupero info path: {_path} | file: {_nomeFile}{Environment.NewLine}{exc}"); _fi = new FileInfo(_path + "\\" + _nomeFile); } #if false try { _fi = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(_path + _nomeFile)); } catch { _fi = new FileInfo(_path + "\\" + _nomeFile); } #endif return _fi; } /// /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente /// come workpath + nomefile /// /// cartella file /// nome file /// indica se il path sia assoluto /// private FileInfo getFileInfoByName(string _path, string _nomeFile, bool absPath) { FileInfo _fi; if (absPath) { _fi = new FileInfo(_path + "\\" + _nomeFile); } else { _fi = getFileInfoByName(_path, _nomeFile); } return _fi; } /// /// setta le directory /// /// private void setDirs(string _path) { _workPath = _path; } #endregion Private Methods } }