Files
A69WD/Src/A69WD/General/cTools.cs
T

482 lines
24 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
namespace A69WD {
public class cTools {
/// <summary>
/// Carica l'assemby da un array di byte
/// </summary>
/// <param name="binaries">Array di byte che definiscono l'assembly</param>
/// <returns>Assembly decodificato dal'array di byte</returns>
public static Assembly LoadAssemblyFromBinaries(byte[] binaries) {
Assembly asm = null;
try {
asm = Assembly.Load(binaries);
} catch { }
return asm;
}
/// <summary>
/// Carica l'assembly dal file indicato
/// </summary>
/// <param name="filename">Nome completo del file assembly da leggere</param>
/// <returns>Assembly decodificato dal file</returns>
public static Assembly LoadAssemblyFromFile(string filename) {
byte[] binaries = ReadFully(filename);
return LoadAssemblyFromBinaries(binaries);
}
/// <summary>
/// Legge il file e ne ritorna l'array di byte che lo compone
/// </summary>
/// <param name="filename">Nome completo del file da leggere</param>
/// <returns>Array con i byte letti dal file</returns>
public static byte[] ReadFully(string filename) {
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] result = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return result;
}
/// <summary>
/// Scrive il testo in un file con append=false e Encoding UTF8
/// </summary>
/// <param name="FullFileName">Nome completo del file da creare/sovrascrivere</param>
/// <param name="Text">StringBuilder con il testo da riportare nel file</param>
public static void WriteTextFile(string FullFileName, StringBuilder Text) {
//System.IO.StreamWriter sw = new System.IO.StreamWriter(FullFileName, false, Encoding.UTF8);
//sw.Write(Text.ToString());
//sw.Flush();
//sw.Close();
WriteTextFile(FullFileName, Text, Encoding.UTF8);
}
public static void WriteTextFile(string FullFileName, StringBuilder Text, Encoding code) {
System.IO.StreamWriter sw = new System.IO.StreamWriter(FullFileName, false, code);
sw.Write(Text.ToString());
sw.Flush();
sw.Close();
}
/// <summary>
/// Metodo che legge un testo da file (UTF8)
/// </summary>
/// <param name="sPath">Path del file da leggere</param>
/// <returns>Testo del file</returns>
public static string ReadTextFile(string sPath) {
//string str = "";
//try {
// if (File.Exists(sPath)) {
// StreamReader reader = File.OpenText(sPath);
// str = reader.ReadToEnd();
// reader.Close();
// reader.Dispose();
// }
//} catch (Exception exception) {
// str = "ERRORE: " + exception.Message;
//}
//return str;
string str = "";
if (File.Exists(sPath)) {
StreamReader reader = File.OpenText(sPath);
str = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
return str;
}
/// <summary>
/// Metodo che legge un testo da file
/// </summary>
/// <param name="FilePath">Path del file da leggere</param>
/// <param name="encoding">Codifica usata nel testo</param>
/// <returns>Testo del file</returns>
public static string ReadTextFile(string FilePath, Encoding encoding) {
System.IO.StreamReader sr = null;
//StringBuilder sb = null;
string txt = "";
try {
//Pass the file path and file name to the StreamReader constructor
sr = new System.IO.StreamReader(FilePath, encoding);
////Read the first line of text
//sb = new StringBuilder();
//string line = sr.ReadLine();
////Continue to read until you reach end of file
//while (line != null) {
// sb.AppendLine(line);
// //Read the next line
// line = sr.ReadLine();
//}
txt = sr.ReadToEnd();
} catch (Exception e) {
throw new Exception("Errore nell'esecuzione di WebTools.Library.Tools.ReadTextFile(string FilePath, Encoding encoding):\n" + e.Message);
//sb = new StringBuilder();
} finally {
//close the file
if (sr != null) {
sr.Close();
sr.Dispose();
sr = null;
}
}
//return sb.ToString();
return txt;
}
/// <summary>
/// Esegue un comando dos dalla shell
/// </summary>
/// <param name="cmd">Comando da eseguire in shell</param>
public static void ExecDosCmd(string cmd) {
string argu = string.Format("/C \"{0}\"", cmd);
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
info.FileName = "cmd.exe";
info.Arguments = argu;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process.Start(info);
}
/// <summary>
/// Esegue un comando dos dalla shell e cattura il risultato
/// </summary>
/// <param name="cmd">Comando da eseguire</param>
/// <param name="args">Argomenti da passare</param>
/// <returns>Testo ritornato dal comando.</returns>
public static string ExecDosCmd(string cmd, string args) {
System.Diagnostics.ProcessStartInfo ProcInfo = new System.Diagnostics.ProcessStartInfo(cmd, args);
ProcInfo.RedirectStandardOutput = true;
ProcInfo.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(ProcInfo);
System.IO.TextReader tr = p.StandardOutput;
string result = tr.ReadToEnd();
tr.Close();
return result;
}
public static bool EditPad(string file) {
try {
System.Diagnostics.Process proc = new System.Diagnostics.Process();
// proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// proc.StartInfo.Verb = "print";
proc.StartInfo.FileName = @"C:\Programmi\My_Tools\Editors\EditPad\EditPad.exe";
proc.StartInfo.Arguments = String.Format(@" {0}", file);
Logger.Log(proc.StartInfo.FileName + proc.StartInfo.Arguments);
proc.Start();
return true;
} catch (Exception ex) { Logger.Log(new object[] { "Error Code: EG0284", ex }); return false; }
}
// public class Pdf {
// public static Boolean PrintPDFs(string pdfFileName)
// {
// try
// {
// Process proc = new Process();
// proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// proc.StartInfo.Verb = "print";
//
// //Define location of adobe reader/command line switches to launch adobe in "print" mode
// proc.StartInfo.FileName = @"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe";
// proc.StartInfo.Arguments = String.Format(@"/p /h {0}", pdfFileName);
// proc.StartInfo.UseShellExecute = false;
// proc.StartInfo.CreateNoWindow = true;
//
// proc.Start();
// proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// if (proc.HasExited == false)
// {
// proc.WaitForExit(10000);
// }
//
// proc.EnableRaisingEvents = true;
//
// proc.Close();
// KillAdobe("AcroRd32");
// return true;
// }
// catch
// {
// return false;
// }
// }
/// <summary>
/// Genera l'elenco dei file nella directory indicata che soddisfano al filtro indicato
/// </summary>
/// <param name="path">directory da analizzare</param>
/// <param name="filtro">Filtro da usare</param>
/// <returns>Array dei path completi, dei file trovati</returns>
public static string[] ElencoFile(string path) { return ElencoFile(path, "*.*", SearchOption.TopDirectoryOnly); }
/// <summary>
/// Genera l'elenco dei file nella directory indicata che soddisfano al filtro indicato
/// </summary>
/// <param name="path">directory da analizzare</param>
/// <param name="filtro">Filtro da usare</param>
/// <returns>Array dei path completi, dei file trovati</returns>
public static string[] ElencoFile(string path, string filtro) { return ElencoFile(path, filtro, SearchOption.TopDirectoryOnly); }
/// <summary>
/// Genera l'elenco dei file nella directory indicata che soddisfano al filtro indicato
/// </summary>
/// <param name="path">directory da analizzare</param>
/// <param name="filtro">Filtro da usare</param>
/// <param name="option"></param>
/// <returns>Array dei path completi, dei file trovati</returns>
public static string[] ElencoFile(string path, string filtro, SearchOption option) { return Directory.GetFiles(path, filtro, option); }
/// <summary>
/// Metodo che analizza il file indicato ed inserisce nella lista tutti i link trovati.
/// </summary>
/// <param name="FileSrcPath">Path del file da analizzare</param>
/// <param name="URLs">Lista di tutti i link trovati</param>
/// <returns>True se tutto Ok, False altrimenti</returns>
public static bool EstraiLink(string FileSrcPath, List<string> links) {
try {
Regex regex = new Regex("(?<=href=\")\\S+?(?=\")");
string input = ReadTextFile(FileSrcPath);
Match matchObj = regex.Match(input);
while (matchObj.Success) {
links.Add(matchObj.Value);
if (matchObj.Groups.Count > 1) {
for (int i = 1; i < matchObj.Groups.Count; i++) {
Group group = matchObj.Groups[i];
if (group.Success) {
links.Add(group.Value);
}
}
}
matchObj = matchObj.NextMatch();
}
return true;
} catch { return false; }
}
/// <summary>
/// Metodo che analizza il file indicato e restituisce l'insieme di tutti i link trovati ordinato e privo di doppioni
/// </summary>
/// <param name="FileSrcPath">Path del file da analizzare</param>
/// <returns>Insieme con i vari link trovati</returns>
public static List<string> GetOrderLink(string FileSrcPath) {
List<string> links = new List<string>();
try {
// Estraggo tutti i link:
if (!EstraiLink(FileSrcPath, links)) return new List<string>();
// Verifico di aver trovato dei link:
if (links.Count == 0) return links;
// Ordino i link estratti:
links.Sort();
// Elimino i duplicati:
string[] tmp = links.ToArray();
links.Clear();
string oldLink = tmp[0];
links.Add(oldLink);
for (int i = 1; i < tmp.Length; i++) {
if (tmp[i] != oldLink) {
oldLink = tmp[1];
links.Add(oldLink);
}
}
return links;
} catch (Exception ex) {
Logger.Log(ex);
return links;
}
}
/// <summary>
/// Metodo che legge il DB dei link dal file di testo in cui è stato salvato.
/// </summary>
/// <returns>Elenco ordinato di tutti i link del DB</returns>
public static List<string> ReadLinkDB(string PathLinkBD) {
StreamReader reader = null;
try {
List<string> buffer = new List<string>();
string row;
reader = new StreamReader(PathLinkBD);
do {
row = reader.ReadLine().Trim();
if (row.StartsWith("http://")) {
buffer.Add(row);
}
} while (!reader.EndOfStream);
reader.Close();
reader = null;
// Ordino
buffer.Sort();
return buffer;
} catch {
if (reader != null) {
reader.Close();
reader = null;
}
return new List<string>();
}
}
/// <summary>
/// Metodo che esegue una copia di backup del file indicato
/// </summary>
/// <param name="FilePath">Path completo del file da backuppare</param>
/// <returns>True se tutto ok, False altrimenti.</returns>
public static bool BackupFile(string FilePath) {
try {
string LinkDBPathBK = Path.GetFileNameWithoutExtension(FilePath) + "_BK_" + DateTime.Now.ToString("yyyy-MM-dd");
LinkDBPathBK = FilePath.Replace(Path.GetFileNameWithoutExtension(FilePath), LinkDBPathBK);
if (!File.Exists(LinkDBPathBK)) File.Move(FilePath, LinkDBPathBK);
return true;
} catch { return false; }
}
/// <summary>
/// Esegue una formattazione del testo ricavato da un file html per scremarlo delle parti html
/// </summary>
/// <param name="txt">Testo da formattare</param>
/// <param name="eliminaTagHtml">Abilitare l'eliminazione di tutti i generici tag </param>
/// <returns>Testo formattato</returns>
public static string FormattaTesto(string txt, bool eliminaTagHtml) {
try {
// Analisi dei tag prima di levarli:
string testo = Regex.Replace(txt, @"<P>", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"</P>", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"<P />", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"<B>", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"</B>", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"<B />", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"<BR>", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"</BR>", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"<br />", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"</div>", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"<div />", "\n", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"<<", "«", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @">>", "»", RegexOptions.IgnoreCase);
// Se richiesto, elimino i tag html:
if (eliminaTagHtml) {
// Preparo la Regex:
string htmlPattern = @"\<[^\>]*\>";
Regex re = new Regex(htmlPattern, RegexOptions.IgnoreCase);
// Applico l'espressione regolare per togliere tutti i tag:
testo = re.Replace(testo, "");
}
// Correggo risultato togliendo doppie linee e caratteri html:
testo = Regex.Replace(testo, @"&nbsp;", " ", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&bull;", " * ", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&lsaquo;", " < ", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&lt;", "<", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&rsaquo;", " > ", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&gt;", ">", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&trade;", "(tm)", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&copy;", "(c)", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&reg;", "(r)", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&frasl;", "/", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&agrave;", "à", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&egrave;", "è", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&igrave;", "ì", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&ograve;", "ò", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&ugrave;", "ù", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#8211;", "–", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#8212;", "—", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#8216;", "‘", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#8217;", "’", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#8220;", "“", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#8221;", "”", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#8230;", "…", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#268;", "Č", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#269;", "č", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#282;", "Ě", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#283;", "ě", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#8232;", " ", RegexOptions.IgnoreCase);
testo = Regex.Replace(testo, @"&#61516;", " ", RegexOptions.IgnoreCase);
// // Remove all others. More can be added, see
// // http://hotwired.lycos.com/webmonkey/reference/special_characters/
// testo = Regex.Replace(testo, @"&(.{2,6});", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//// Correggo accenti per formati sbagliati:
//while (testo.Contains("à")) { testo = testo.Replace("à", "à"); }
//while (testo.Contains("è")) { testo = testo.Replace("è", "è"); }
//while (testo.Contains("é")) { testo = testo.Replace("é", "é"); }
//while (testo.Contains("ì")) { testo = testo.Replace("ì", "ì"); }
//while (testo.Contains("ò")) { testo = testo.Replace("ò", "ò"); }
//while (testo.Contains("ù")) { testo = testo.Replace("ù", "ù"); }
//while (testo.Contains("’")) { testo = testo.Replace("’", "'"); }
// Correggo scritto:
testo = testo.Replace("\r", "");
while (testo.Contains("\t")) { testo = testo.Replace("\t", " "); }
while (testo.Contains("...")) { testo = testo.Replace("...", "…"); }
while (testo.Contains("….")) { testo = testo.Replace("….", "…"); }
while (testo.Contains("……")) { testo = testo.Replace("……", "…"); }
while (testo.Contains(" ")) { testo = testo.Replace(" ", " "); }
while (testo.Contains(" \n")) { testo = testo.Replace(" \n", "\n"); }
while (testo.Contains("\n ")) { testo = testo.Replace("\n ", "\n"); }
while (testo.Contains("\n\n")) { testo = testo.Replace("\n\n", "\n"); }
return testo;
} catch (Exception ex) { return string.Format(" Errore: Errore durante la formattazione del testo:\n{0}\n\n", ex.Message); }
}
/// <summary>
/// Muove i file indicati, nella directory di destinazione indicata
/// </summary>
/// <param name="IndexFiles">Array con l'elenco dei file da spostare</param>
/// <param name="PathDestination">Path della directory in cui spostare i file</param>
/// <returns>True se tutto OK, False altrimenti.</returns>
public static bool MoveFiles(string[] Files, string PathDestination) {
// Sposta tutti i file indicati nella directory indicata:
try {
foreach (string file in Files) {
string dst = Path.Combine(PathDestination, Path.GetFileName(file));
if (System.IO.File.Exists(dst)) System.IO.File.Delete(dst);
File.Move(file, dst);
}
return true;
} catch { return false; }
}
public static bool WriteStyleSheet(string FullFileName) {
try {
StringBuilder sb = new StringBuilder();
sb.Append("BODY{\n\tmargin-left : 5px;\n\tmargin-right : 5px;\n\tcolor : #000099;\n\tfont-family : Verdana,Arial,Helvetica;\n\tbackground-color : #F4F4F4;\n}\n.Title {\n\ttext-align : center; \n\tfont-family : \"Helvetica\";\n\tfont-size : x-large;\n}\n.SubTitle {\n\ttext-align : center; \n\ttext-indent : 16px;\n\tfont-family : \"Helvetica\";\n\tfont-size : large;\n\tfont-style : italic;\n}\n.Property {\n\ttext-align : justify; \n\ttext-indent : 25px;\n\tfont-style : italic;\n}\n.Origine {\n\ttext-align : justify; \n\ttext-indent : 25px;\n\tfont-style : italic;\n}\n.Autore {\n\ttext-align : justify; \n\ttext-indent : 25px;\n\tfont-style : italic;\n}\n.Data {\n\ttext-align : justify; \n\ttext-indent : 25px;\n\tfont-style : italic;\n}\n.Trama {\n\ttext-align : justify; \n\ttext-indent : 12px;\n\tcolor : #000000;\n}\n.Menu {\n\ttext-align : right; \n\ttext-indent : 12px;\n\tcolor : #000000;\n}\n.MsgTitle {\n\ttext-align : justify; \n\ttext-indent : 25px;\n\tfont-style : italic;\n}\n.MsgText {\n\ttext-align : justify; \n\ttext-indent : 12px;\n\tcolor : #000000;\n}\n.ReportTitle {\n\ttext-align : center; \n\tfont-family : \"Helvetica\";\n\tfont-size : x-large;\n}\n.ReportText {\n\ttext-align : justify; \n\ttext-indent : 25px;\n\tfont-style : italic;\n}\n.Menu_Row {\n\tfont-size:70%;\n\twhite-space:nowrap;\n}\n.Menu_sx {\n\ttext-align:left; width:50%; float: left;\n}\n.Menu_dx {\n\ttext-align:right; width:50%; float: right;\n}\n");
WriteTextFile(FullFileName, sb);
return true;
} catch (Exception ex) {
Logger.Log(new object[] { "Error Code: eBook000", "Errore in ATlib.Tools.WriteStyleS(FullFileName)", ex });
return false;
}
}
} // class Tools
} // namespace A69WD