1328 lines
46 KiB
C#
1328 lines
46 KiB
C#
using ICSharpCode.SharpZipLib.Zip;
|
|
using NLog;
|
|
using System;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Net;
|
|
|
|
namespace SteamWare.IO
|
|
{
|
|
/// <summary>
|
|
/// Accesso in lettura e scrittura al filesystem per gestione files upload e download
|
|
/// </summary>
|
|
public class fileMover
|
|
{
|
|
#region Public Fields
|
|
|
|
/// <summary>
|
|
/// versione statica (singleton) del'oggetto fileMover
|
|
/// </summary>
|
|
public static fileMover obj = new fileMover();
|
|
|
|
/// <summary>
|
|
/// oggetto WebClient
|
|
/// </summary>
|
|
public WebClient WebCli;
|
|
|
|
#endregion Public Fields
|
|
|
|
#region Public Constructors
|
|
|
|
/// <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)
|
|
{
|
|
if (Log == null)
|
|
{
|
|
Log = LogManager.GetCurrentClassLogger();
|
|
}
|
|
setDirs(_path);
|
|
WebCli = new WebClient();
|
|
}
|
|
|
|
/// <summary>
|
|
/// metodo di avvio empty
|
|
/// </summary>
|
|
public fileMover()
|
|
{
|
|
if (Log == null)
|
|
{
|
|
Log = LogManager.GetCurrentClassLogger();
|
|
}
|
|
WebCli = new WebClient();
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Methods
|
|
|
|
/// <summary>
|
|
/// Effettua copia files da locale a rete con auth (Local 2 Network)...
|
|
/// </summary>
|
|
/// <param name="pathSource"></param>
|
|
/// <param name="pathDest"></param>
|
|
/// <param name="credentialsSource"></param>
|
|
/// <param name="credentialsDest"></param>
|
|
/// <param name="fileSource"></param>
|
|
/// <param name="fileDest"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua copia files via rete con auth (Net 2 Net)...
|
|
/// </summary>
|
|
/// <param name="pathSource"></param>
|
|
/// <param name="pathDest"></param>
|
|
/// <param name="credentialsSource"></param>
|
|
/// <param name="credentialsDest"></param>
|
|
/// <param name="fileSource"></param>
|
|
/// <param name="fileDest"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// elimina la folder indicata
|
|
/// </summary>
|
|
/// <param name="PathOfDir2Delete">Path della fodler da eliminare</param>
|
|
/// <param name="recursive">Indica se cancellare in modo ricorsivo</param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <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 (Exception ex)
|
|
{
|
|
ret = false;
|
|
Log.Error(string.Format("Non sono riuscito ad eliminare file: eccezione {0}", ex));
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Copia il contenuto directory da From a To (opzionalmente in modo ricorsivo)...
|
|
/// </summary>
|
|
/// <param name="sourceDirName">Nome dir sorgente</param>
|
|
/// <param name="destDirName">Nome dir destinazione</param>
|
|
/// <param name="copySubDirs">Indica se copiare ricorsivamente</param>
|
|
/// <param name="overwrite">Indica se sovrascrivere i dati (default = true)</param>
|
|
/// <returns></returns>
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <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>
|
|
/// restituisce la stringa completa e corretta del filepath del server (anche con vDir)
|
|
/// </summary>
|
|
/// <param name="pathRel">path relativo alla cartella iis dell'applicativo</param>
|
|
/// <returns>path fisico tradotto</returns>
|
|
public static string getFilePath(string pathRel)
|
|
{
|
|
return System.Web.HttpContext.Current.Server.MapPath(pathRel);
|
|
}
|
|
|
|
/// <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 (Exception ex)
|
|
{
|
|
ret = false;
|
|
Log.Error(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex));
|
|
}
|
|
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 (Exception ex)
|
|
{
|
|
ret = false;
|
|
Log.Error(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex));
|
|
}
|
|
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(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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// elimina il file + vecchio
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// ottiene il dataset dei files presenti nella directory indicata all'istanziazione dell'oggetto
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public DataLayer_generic.filesDataTable elencoFiles()
|
|
{
|
|
DirectoryInfo _di = checkDir();
|
|
FileInfo[] _files = _di.GetFiles();
|
|
DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files);
|
|
return _dsEF;
|
|
}
|
|
|
|
/// <summary>
|
|
/// ottiene il dataset dei files DEL TIPO "like {param}" presenti nella directory indicata
|
|
/// all'istanziazione dell'oggetto
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public DataLayer_generic.filesDataTable elencoFiles(string _param)
|
|
{
|
|
DirectoryInfo _di = checkDir();
|
|
FileInfo[] _files = _di.GetFiles(_param);
|
|
DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files);
|
|
return _dsEF;
|
|
}
|
|
|
|
/// <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>
|
|
/// ottiene il dataset dei files presenti nella directory indicata esplicitamente
|
|
/// </summary>
|
|
/// <param name="directory">
|
|
/// dir da indicizzare... già mappata! ( es SteamwareStrings.getFilePath(...) )
|
|
/// </param>
|
|
/// <returns></returns>
|
|
public DataLayer_generic.filesDataTable elencoFilesDir(string directory)
|
|
{
|
|
_workPath = directory;
|
|
return elencoFiles();
|
|
}
|
|
|
|
/// <summary>
|
|
/// elenco sub-directory array di oggetti FileInfo filtrati per parametro
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public DirectoryInfo[] elencoSubdir_DI()
|
|
{
|
|
DirectoryInfo _di = checkDir();
|
|
return _di.GetDirectories();
|
|
}
|
|
|
|
/// <summary>
|
|
/// elenco sub-directory array di oggetti FileInfo filtrati per parametro
|
|
/// </summary>
|
|
/// <param name="_param"></param>
|
|
/// <returns></returns>
|
|
public DirectoryInfo[] elencoSubdir_DI(string _param)
|
|
{
|
|
DirectoryInfo _di = checkDir();
|
|
return _di.GetDirectories(_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
|
|
{ }
|
|
if (fatto)
|
|
{
|
|
Log.Info($"Eliminazione file {_nomeFile} eseguita");
|
|
}
|
|
else
|
|
{
|
|
Log.Info($"impossibile Eliminare il file {_nomeFile}");
|
|
}
|
|
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;
|
|
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;
|
|
}
|
|
|
|
/// <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;
|
|
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;
|
|
}
|
|
|
|
/// <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, true);
|
|
try
|
|
{
|
|
_fi.CopyTo(_pathTo + _nomeFile, true);
|
|
_fi.Delete();
|
|
fatto = true;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine("{0} Exception caught.", e);
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// scrive il file dallo stream byte[] inviato
|
|
/// </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, 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;
|
|
}
|
|
|
|
/// <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>
|
|
/// imposta la dir di lavoro impostandola dal mapPath corretto della web app... (come
|
|
/// subfolder della web app)
|
|
/// </summary>
|
|
/// <param name="_path"></param>
|
|
public void setDirectoryMapPath(string _path)
|
|
{
|
|
setDirs(System.Web.HttpContext.Current.Server.MapPath(_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 (Exception e)
|
|
{
|
|
Log.Error(string.Format("Errore in creazione file zip con parametri {0} e {1}: {2}", regExp, outZipFileName, e));
|
|
}
|
|
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 Public Methods
|
|
|
|
#region Protected Fields
|
|
|
|
/// <summary>
|
|
/// path di lavoro dei metodi leggi/scrivi
|
|
/// </summary>
|
|
protected string _workPath;
|
|
|
|
#endregion Protected Fields
|
|
|
|
#region Protected Methods
|
|
|
|
/// <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>
|
|
/// Recupera path correttamente (se fisico o virtuale
|
|
/// </summary>
|
|
/// <param name="path"></param>
|
|
/// <returns></returns>
|
|
protected string GetPath(string path)
|
|
{
|
|
if (Path.IsPathRooted(path))
|
|
{
|
|
return path;
|
|
}
|
|
// altrimenti MapPath!
|
|
return System.Web.HttpContext.Current.Server.MapPath(path);
|
|
}
|
|
|
|
/// <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>
|
|
/// 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, 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
|
|
|
|
/// <summary>
|
|
/// restituisce una tab di files dato l'elenco dei files
|
|
/// </summary>
|
|
/// <param name="_files"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// cerca di caricare la directoryInfo o da httpcontext-application re-position o
|
|
/// direttamente come workpath
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private DirectoryInfo getDirectoryInfo()
|
|
{
|
|
DirectoryInfo _di;
|
|
try
|
|
{
|
|
_di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath));
|
|
}
|
|
catch
|
|
{
|
|
_di = new DirectoryInfo(_workPath);
|
|
}
|
|
return _di;
|
|
}
|
|
|
|
/// <summary>
|
|
/// imposta la directory richiesta...
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente
|
|
/// come workpath + nomefile
|
|
/// </summary>
|
|
/// <param name="_nomeFile"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente
|
|
/// come workpath + nomefile
|
|
/// </summary>
|
|
/// <param name="_path">The _path.</param>
|
|
/// <param name="_nomeFile">The _nome file.</param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <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>
|
|
/// <param name="absPath">indica se il path sia assoluto</param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// setta le directory
|
|
/// </summary>
|
|
/// <param name="_path"></param>
|
|
private void setDirs(string _path)
|
|
{
|
|
_workPath = _path;
|
|
}
|
|
|
|
#endregion Private Methods
|
|
}
|
|
} |