77 lines
2.5 KiB
C#
77 lines
2.5 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.IO.Compression;
|
|
using System.Linq;
|
|
using Google.Protobuf;
|
|
|
|
namespace bts.support {
|
|
static class FileUtils {
|
|
public static bool try_delete(string path) {
|
|
try {
|
|
if (File.Exists(path)) {
|
|
File.Delete(path);
|
|
}
|
|
else if (Directory.Exists(path)) {
|
|
Directory.Delete(path, true);
|
|
}
|
|
}
|
|
catch {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public static ByteString read_and_gzip(string path) {
|
|
if (File.Exists(path)) {
|
|
try {
|
|
using (var fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite /*Note: ReadWrite is more permissive than Read*/))
|
|
using (var ms = new MemoryStream())
|
|
using (var gz = new GZipStream(ms, CompressionMode.Compress, true)) {
|
|
fs.CopyTo(gz);
|
|
gz.Close();
|
|
return ByteString.CopyFrom(ms.GetBuffer(), 0, (int)ms.Length);
|
|
}
|
|
}
|
|
catch (Exception e) {
|
|
Log.Gen.error($"Failed to read file '{path}' -- {e.Message}");
|
|
return ByteString.Empty;
|
|
}
|
|
}
|
|
return ByteString.Empty;
|
|
}
|
|
|
|
|
|
// If input exists compress it and add a .gz extension
|
|
// original file is deleted
|
|
public static string gzip_file_in_place(string file) {
|
|
if (File.Exists(file)) {
|
|
string destination = file + ".gz";
|
|
using (var input = File.OpenRead(file)) {
|
|
using (var output = File.OpenWrite(destination)) {
|
|
using (var writer = new GZipStream(output, CompressionMode.Compress)) {
|
|
input.CopyTo(writer);
|
|
}
|
|
}
|
|
}
|
|
try_delete(file);
|
|
return destination;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// Delete the oldest files matching pattern (*.txt) keeping {count} files
|
|
public static void keep_n_matching_files(string directory, string pattern, int count) {
|
|
var to_delete =
|
|
Directory.GetFiles(directory, pattern)
|
|
.Select(f => new { name = f, modified = File.GetLastWriteTimeUtc(f) })
|
|
.OrderBy(f => f.modified)
|
|
.Reverse()
|
|
.Skip(count);
|
|
|
|
foreach (var f in to_delete) {
|
|
try_delete(f.name);
|
|
}
|
|
}
|
|
}
|
|
}
|