PTMagic/Core/Helper/FileHelper.cs

96 lines
2.5 KiB
C#
Raw Permalink Normal View History

2018-05-22 10:11:50 +02:00
using System;
using System.IO;
using Core.Main;
namespace Core.Helper
{
public static class FileHelper
{
public static void WriteTextToFile(string folderPath, string fileName, string text)
{
2018-05-22 10:11:50 +02:00
FileHelper.WriteTextToFile(folderPath, fileName, text, Constants.confMinDate, Constants.confMinDate);
}
public static void WriteTextToFile(string folderPath, string fileName, string text, DateTime creationTime, DateTime lastWriteTime)
{
if (!Directory.Exists(folderPath))
{
2018-05-22 10:11:50 +02:00
Directory.CreateDirectory(folderPath);
}
File.WriteAllText(folderPath + fileName, text);
if (creationTime != Constants.confMinDate)
{
2018-05-22 10:11:50 +02:00
File.SetCreationTimeUtc(folderPath + fileName, creationTime);
}
if (lastWriteTime != Constants.confMinDate)
{
2018-05-22 10:11:50 +02:00
File.SetLastWriteTimeUtc(folderPath + fileName, lastWriteTime);
}
}
public static void CreateBackup(string filePath, string backupFolder)
{
2018-05-22 10:11:50 +02:00
FileHelper.CreateBackup(filePath, backupFolder, "");
}
public static void CreateBackup(string filePath, string backupFolder, string backupFileName)
{
if (!Directory.Exists(backupFolder))
{
2018-05-22 10:11:50 +02:00
Directory.CreateDirectory(backupFolder);
}
FileInfo file = new FileInfo(filePath);
string backupFilePath = backupFolder + DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss") + "_" + file.Name;
if (!backupFileName.Equals(""))
{
2018-05-22 10:11:50 +02:00
backupFilePath = backupFolder + backupFileName;
}
File.Copy(file.FullName, backupFilePath, true);
}
public static void CleanupFilesMinutes(string folderPath, int maxMinutes)
{
if (!Directory.Exists(folderPath))
{
2018-05-22 10:11:50 +02:00
Directory.CreateDirectory(folderPath);
}
DirectoryInfo folder = new DirectoryInfo(folderPath);
foreach (FileInfo file in folder.GetFiles())
{
DateTime maxAge = DateTime.UtcNow.AddMinutes(-maxMinutes);
2018-05-22 10:11:50 +02:00
if (file.LastWriteTimeUtc < maxAge)
{
2018-05-22 10:11:50 +02:00
File.Delete(file.FullName);
}
}
}
public static void CleanupFiles(string folderPath, int maxHours)
{
if (!Directory.Exists(folderPath))
{
2018-05-22 10:11:50 +02:00
Directory.CreateDirectory(folderPath);
}
DirectoryInfo folder = new DirectoryInfo(folderPath);
foreach (FileInfo file in folder.GetFiles())
{
DateTime maxAge = DateTime.UtcNow.AddHours(-(maxHours + 1));
2018-05-22 10:11:50 +02:00
if (file.LastWriteTimeUtc < maxAge)
{
2018-05-22 10:11:50 +02:00
File.Delete(file.FullName);
}
}
}
}
}