2 using System.Security.Cryptography;
10 public static class FileInfoExtensions
17 public static string GetNameWithoutExtension(
this FileInfo f)
19 if (f == null)
return "";
20 if (!f.Extension.IsNullOrWhiteSpace())
22 return f.Name.Left(f.Name.Length - f.Extension.Length);
33 public static string ReadFileToString(
this FileInfo f)
35 StreamReader streamReader = f.OpenText();
36 string Data = streamReader.ReadToEnd();
38 streamReader.Dispose();
46 public static bool CheckExists(
this FileInfo FI)
48 return new FileInfo(FI.FullName).Exists;
56 public static string GetMD5Hash(
this FileInfo FI)
58 byte[] hashBytes = null;
61 using (var inputFileStream = FI.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
63 MD5 md5 =
System.Security.Cryptography.MD5.Create();
64 hashBytes = md5.ComputeHash(inputFileStream);
66 return string.Join(
"", hashBytes.Select(B =>
"{0:x2}".Build(B)).ToArray());
72 throw new Exception(
"Cant calculate MD5 has of file {0}.".Build(FI.FullName), E);
82 public static T XMLDeserialize<T>(
this FileInfo FI)
84 using (FileStream ms = FI.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
88 return (T)
new System.Xml.Serialization.XmlSerializer(typeof(T)).Deserialize(ms);
93 Exception Ex =
new Exception(
"Could not deserialize {0} from XML data in file: {1}".Build(typeof(T).Name, FI.FullName), E);
107 public static bool CheckFileLocked(
this FileInfo file)
109 FileStream stream = null;
113 stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
117 if (!file.CheckExists())
119 throw new FileNotFoundException(
"File {0} not found".Build(file.FullName), file.FullName);
138 public static bool CheckCanRead(
this FileInfo file)
144 stream = File.Open(file.FullName, FileMode.Open, FileAccess.Read);
158 public static void MoveTo(
this FileInfo Source, FileInfo Dest)
160 Source.MoveTo(Dest.FullName);
168 public static void CopyTo(
this FileInfo Source, FileInfo Dest)
170 Source.CopyTo(Dest.FullName);