namespace VideoBrowser.Helpers { using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; /// /// Defines the /// public static class FileHelper { #region Methods /// /// Returns valid file name. /// /// The filename to validate. public static string GetValidFilename(string filename) { var illegalChars = Path.GetInvalidFileNameChars(); // Check if filename contains illegal characters // Returning true for some reason: valid = filename.Any(x => illegalChars.Contains(x)); var valid = filename.IndexOfAny(illegalChars) <= -1; if (!valid) { string new_filename = YoutubeHelper.FormatTitle(filename); filename = new_filename; } return filename; } /// /// Attempts to delete given file(s), ignoring exceptions for 10 tries, with 2 second delay between each try. /// /// The files to delete. public static void DeleteFiles(params string[] files) { new Thread(delegate () { var dict = new Dictionary(); var keys = new List(); foreach (string file in files) { dict.Add(file, 0); keys.Add(file); } while (dict.Count > 0) { foreach (string key in keys) { try { if (File.Exists(key)) { File.Delete(key); } // Remove file from dictionary since it either got deleted // or it doesn't exist anymore. dict.Remove(key); } catch { if (dict[key] == 10) { dict.Remove(key); } else { dict[key]++; } } } Thread.Sleep(2000); } }).Start(); } /// /// The GetDirectorySize /// /// The directory /// The public static long GetDirectorySize(string directory) { return Directory .GetFiles(directory, "*.*", SearchOption.AllDirectories) .Sum(f => new FileInfo(f).Length); } /// /// The GetDirectorySizeFormatted /// /// The directory /// The public static string GetDirectorySizeFormatted(string directory) => FormatString.FormatFileSize(GetDirectorySize(directory)); /// /// Calculates the ETA (estimated time of accomplishment). /// /// The speed as bytes. (Bytes per second?) /// The total amount of bytes. /// The amount of downloaded bytes. /// The public static long GetETA(int speed, long totalBytes, long downloadedBytes) { if (speed == 0) { return 0; } var remainBytes = totalBytes - downloadedBytes; return remainBytes / speed; } /// /// Returns a long of the file size from given file in bytes. /// /// The file to get file size from. /// The public static long GetFileSize(string file) => !File.Exists(file) ? 0 : new FileInfo(file).Length; /// /// Returns an formatted string of the given file's size. /// /// The file /// The public static string GetFileSizeFormatted(string file) => FormatString.FormatFileSize(GetFileSize(file)); #endregion Methods } }