You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.5KB

  1. using System.Text;
  2. namespace ToolsServices
  3. {
  4. public static class TxtService
  5. {
  6. public static string ExtractTextFromTxt(string filePath)
  7. {
  8. LoggerService.LogInfo($"TxtService.ExtractTextFromTxt : {filePath}");
  9. if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
  10. {
  11. LoggerService.LogInfo($"Le fichier n'existe pas : {filePath}");
  12. return "";
  13. }
  14. if(!IsTextFile(filePath))
  15. {
  16. LoggerService.LogInfo($"Le fichier est illisible : {filePath}");
  17. return "";
  18. }
  19. return File.ReadAllText(filePath, Encoding.UTF8);
  20. }
  21. public static bool CreateTextFile(string filePath, string content)
  22. {
  23. LoggerService.LogInfo($"TxtService.CreateTextFile");
  24. try
  25. {
  26. if(File.Exists(filePath))
  27. File.Delete(filePath);
  28. File.WriteAllText(filePath, content, new UTF8Encoding(true));
  29. return true;
  30. }
  31. catch (Exception ex)
  32. {
  33. LoggerService.LogError($"TxtService.CreateTextFile : {ex.Message}");
  34. return false;
  35. }
  36. }
  37. private static bool IsTextFile(string path, int sampleSize = 1024)
  38. {
  39. LoggerService.LogInfo($"TxtService.IsTextFile : {path}");
  40. byte[] buffer = new byte[sampleSize];
  41. int bytesRead;
  42. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
  43. {
  44. bytesRead = fs.Read(buffer, 0, buffer.Length);
  45. }
  46. // Si le fichier est vide, on le considère comme texte
  47. if (bytesRead == 0) return true;
  48. // Vérifier s'il contient beaucoup de caractères non imprimables
  49. int nonPrintableCount = 0;
  50. for (int i = 0; i < bytesRead; i++)
  51. {
  52. byte b = buffer[i];
  53. // Autorise : tab(9), LF(10), CR(13), caractères imprimables ASCII (32-126) et UTF-8 multibyte (>127)
  54. if (!(b == 9 || b == 10 || b == 13 || (b >= 32 && b <= 126) || b >= 128))
  55. {
  56. nonPrintableCount++;
  57. }
  58. }
  59. // Seuil : moins de 5% de caractères non imprimables => fichier texte
  60. double ratio = (double)nonPrintableCount / bytesRead;
  61. return ratio < 0.05;
  62. }
  63. }
  64. }