Changeset 1709
- Timestamp:
- 1/28/2010 3:37:54 AM (3 years ago)
- Location:
- branches/eraser6/CodeReview
- Files:
-
- 11 edited
- 1 moved
-
Eraser.DefaultPlugins/FileSystems/Windows.cs (modified) (2 diffs)
-
Eraser.Manager/DirectExecutor.cs (modified) (2 diffs)
-
Eraser.Manager/FileSystem.cs (modified) (2 diffs)
-
Eraser.Manager/Task.cs (modified) (2 diffs)
-
Eraser.Util/BlackBox.cs (modified) (1 diff)
-
Eraser.Util/Eraser.Util.csproj (modified) (2 diffs)
-
Eraser.Util/ExtensionMethods/IO.cs (modified) (2 diffs)
-
Eraser.Util/FileSize.cs (moved) (moved from branches/eraser6/CodeReview/Eraser.Util/File.cs) (3 diffs)
-
Eraser.Util/Localisation.cs (modified) (2 diffs)
-
Eraser/Program.cs (modified) (2 diffs)
-
Eraser/TaskDataSelectionForm.cs (modified) (2 diffs)
-
Eraser/UpdateForm.cs (modified) (4 diffs)
Legend:
- Unmodified
- Added
- Removed
-
branches/eraser6/CodeReview/Eraser.DefaultPlugins/FileSystems/Windows.cs
r1702 r1709 210 210 211 211 foreach (FileInfo file in info.GetFiles()) 212 if ( Util.File.IsProtectedSystemFile(file.FullName))212 if (file.IsProtectedSystemFile()) 213 213 log.LastSessionEntries.Add(new LogEntry(S._("{0} did not have " + 214 214 "its cluster tips erased, because it is a system file", … … 230 230 try 231 231 { 232 foreach (string i in Util.File.GetADSes(file))232 foreach (string i in file.GetADSes()) 233 233 files.Add(file.FullName + ':' + i); 234 234 -
branches/eraser6/CodeReview/Eraser.Manager/DirectExecutor.cs
r1701 r1709 29 29 30 30 using Eraser.Util; 31 using Eraser.Util.ExtensionMethods; 31 32 using System.Security.Principal; 32 33 using System.Runtime.Serialization; … … 424 425 //Set the folder's compression flag off since we want to use as much 425 426 //space as possible 426 if ( Eraser.Util.File.IsCompressed(info.FullName))427 Eraser.Util.File.SetCompression(info.FullName, false);427 if (info.IsCompressed()) 428 info.Uncompress(); 428 429 429 430 ProgressManager mainProgress = new ProgressManager(); -
branches/eraser6/CodeReview/Eraser.Manager/FileSystem.cs
r1681 r1709 65 65 } 66 66 while (info != null && (Directory.Exists(resultPrefix + result) || 67 System.IO.File.Exists(resultPrefix + result)));67 File.Exists(resultPrefix + result))); 68 68 return resultPrefix + result; 69 69 } … … 124 124 125 125 int index = prng.Next(entries.Count - 1); 126 if (( System.IO.File.GetAttributes(entries[index]) & FileAttributes.Directory) != 0)126 if ((File.GetAttributes(entries[index]) & FileAttributes.Directory) != 0) 127 127 { 128 128 DirectoryInfo dir = new DirectoryInfo(entries[index]); -
branches/eraser6/CodeReview/Eraser.Manager/Task.cs
r1701 r1709 30 30 31 31 using Eraser.Util; 32 using Eraser.Util.ExtensionMethods; 32 33 33 34 namespace Eraser.Manager … … 448 449 { 449 450 //Get the ADS names 450 IList<string> adses = Util.File.GetADSes(new FileInfo(file));451 IList<string> adses = new FileInfo(file).GetADSes(); 451 452 452 453 //Then prepend the path. -
branches/eraser6/CodeReview/Eraser.Util/BlackBox.cs
r1681 r1709 304 304 305 305 string stackTracePath = System.IO.Path.Combine(Path, StackTraceFileName); 306 if (! System.IO.File.Exists(stackTracePath))306 if (!File.Exists(stackTracePath)) 307 307 { 308 308 Delete(); -
branches/eraser6/CodeReview/Eraser.Util/Eraser.Util.csproj
r1701 r1709 88 88 <Compile Include="StreamInfo.cs" /> 89 89 <Compile Include="SystemInfo.cs" /> 90 <Compile Include="File.cs" />91 90 <Compile Include="Theming.cs" /> 92 91 <Compile Include="VolumeInfo.cs" /> … … 103 102 <ItemGroup> 104 103 <Compile Include="ConsoleWindow.cs" /> 104 <Compile Include="FileSize.cs" /> 105 105 <Compile Include="NativeMethods\DbgHelp.cs" /> 106 106 <Compile Include="NativeMethods\Mpr.cs" /> -
branches/eraser6/CodeReview/Eraser.Util/ExtensionMethods/IO.cs
r1529 r1709 25 25 26 26 using System.IO; 27 using System.Drawing; 28 using System.Runtime.InteropServices; 29 using Microsoft.Win32.SafeHandles; 30 using System.Globalization; 31 using System.Windows.Forms; 27 32 28 33 namespace Eraser.Util.ExtensionMethods … … 74 79 throw new ArgumentException("Unknown FileSystemInfo type."); 75 80 } 81 82 /// <summary> 83 /// Compacts the file path, fitting in the given width. 84 /// </summary> 85 /// <param name="info">The <see cref="System.IO.FileSystemObject"/> that should 86 /// get a compact path.</param> 87 /// <param name="newWidth">The target width of the text.</param> 88 /// <param name="drawFont">The font used for drawing the text.</param> 89 /// <returns>The compacted file path.</returns> 90 public static string GetCompactPath(this FileSystemInfo info, int newWidth, Font drawFont) 91 { 92 using (Control ctrl = new Control()) 93 { 94 //First check if the source string is too long. 95 Graphics g = ctrl.CreateGraphics(); 96 string longPath = info.FullName; 97 int width = g.MeasureString(longPath, drawFont).ToSize().Width; 98 if (width <= newWidth) 99 return longPath; 100 101 //It is, shorten it. 102 int aveCharWidth = width / longPath.Length; 103 int charCount = newWidth / aveCharWidth; 104 StringBuilder builder = new StringBuilder(); 105 builder.Append(longPath); 106 builder.EnsureCapacity(charCount); 107 108 while (g.MeasureString(builder.ToString(), drawFont).Width > newWidth) 109 { 110 if (!NativeMethods.PathCompactPathEx(builder, longPath, 111 (uint)charCount--, 0)) 112 { 113 return string.Empty; 114 } 115 } 116 117 return builder.ToString(); 118 } 119 } 120 121 /// <summary> 122 /// Checks whether the path given is compressed. 123 /// </summary> 124 /// <param name="info">The <see cref="System.IO.FileInfo"/> object</param> 125 /// <returns>True if the file or folder is compressed.</returns> 126 public static bool IsCompressed(this FileSystemInfo info) 127 { 128 ushort compressionStatus = 0; 129 uint bytesReturned = 0; 130 131 using (SafeFileHandle handle = NativeMethods.CreateFile(info.FullName, 132 NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 133 0, IntPtr.Zero, NativeMethods.OPEN_EXISTING, 134 NativeMethods.FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero)) 135 { 136 if (NativeMethods.DeviceIoControl(handle, NativeMethods.FSCTL_GET_COMPRESSION, 137 IntPtr.Zero, 0, out compressionStatus, sizeof(ushort), out bytesReturned, 138 IntPtr.Zero)) 139 { 140 return compressionStatus != NativeMethods.COMPRESSION_FORMAT_NONE; 141 } 142 } 143 144 return false; 145 } 146 147 /// <summary> 148 /// Compresses the given file. 149 /// </summary> 150 /// <param name="info">The File to compress.</param> 151 /// <returns>The success ofthe compression</returns> 152 public static bool Compress(this FileSystemInfo info) 153 { 154 return SetCompression(info.FullName, true); 155 } 156 157 /// <summary> 158 /// Uncompresses the given file. 159 /// </summary> 160 /// <param name="info">The File to uncompress.</param> 161 /// <returns>The success ofthe uncompression</returns> 162 public static bool Uncompress(this FileSystemInfo info) 163 { 164 return SetCompression(info.FullName, false); 165 } 166 167 /// <summary> 168 /// Sets whether the file system object pointed to by path is compressed. 169 /// </summary> 170 /// <param name="path">The path to the file or folder.</param> 171 /// <returns>True if the file or folder has its compression value set.</returns> 172 private static bool SetCompression(string path, bool compressed) 173 { 174 ushort compressionStatus = compressed ? 175 NativeMethods.COMPRESSION_FORMAT_DEFAULT : 176 NativeMethods.COMPRESSION_FORMAT_NONE; 177 uint bytesReturned = 0; 178 179 using (SafeFileHandle handle = NativeMethods.CreateFile(path, 180 NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 181 0, IntPtr.Zero, NativeMethods.OPEN_EXISTING, 182 NativeMethods.FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero)) 183 { 184 return NativeMethods.DeviceIoControl(handle, NativeMethods.FSCTL_SET_COMPRESSION, 185 ref compressionStatus, sizeof(ushort), IntPtr.Zero, 0, out bytesReturned, 186 IntPtr.Zero); 187 } 188 } 189 190 /// <summary> 191 /// Uses SHGetFileInfo to retrieve the description for the given file, 192 /// folder or drive. 193 /// </summary> 194 /// <param name="info">The file system object to query the description of.</param> 195 /// <returns>A string containing the description</returns> 196 public static string GetDescription(this FileSystemInfo info) 197 { 198 NativeMethods.SHFILEINFO shfi = new NativeMethods.SHFILEINFO(); 199 NativeMethods.SHGetFileInfo(info.FullName, 0, ref shfi, Marshal.SizeOf(shfi), 200 NativeMethods.SHGetFileInfoFlags.SHGFI_DISPLAYNAME); 201 return shfi.szDisplayName; 202 } 203 204 /// <summary> 205 /// Uses SHGetFileInfo to retrieve the icon for the given file, folder or 206 /// drive. 207 /// </summary> 208 /// <param name="info">The file system object to query the description of.</param> 209 /// <returns>An Icon object containing the bitmap</returns> 210 public static Icon GetIcon(this FileSystemInfo info) 211 { 212 NativeMethods.SHFILEINFO shfi = new NativeMethods.SHFILEINFO(); 213 NativeMethods.SHGetFileInfo(info.FullName, 0, ref shfi, Marshal.SizeOf(shfi), 214 NativeMethods.SHGetFileInfoFlags.SHGFI_SMALLICON | 215 NativeMethods.SHGetFileInfoFlags.SHGFI_ICON); 216 217 if (shfi.hIcon != IntPtr.Zero) 218 return Icon.FromHandle(shfi.hIcon); 219 else 220 throw new IOException(string.Format(CultureInfo.CurrentCulture, 221 "Could not load file icon from {0}", info.FullName), 222 Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error())); 223 } 224 225 /// <summary> 226 /// Determines if a given file is protected by SFC. 227 /// </summary> 228 /// <param name="info">The file systme object to check.</param> 229 /// <returns>True if the file is protected.</returns> 230 public static bool IsProtectedSystemFile(this FileSystemInfo info) 231 { 232 return NativeMethods.SfcIsFileProtected(IntPtr.Zero, info.FullName); 233 } 234 235 /// <summary> 236 /// Gets the list of ADSes of the given file. 237 /// </summary> 238 /// <param name="info">The FileInfo object with the file path etc.</param> 239 /// <returns>A list containing the names of the ADSes of each file. The 240 /// list will be empty if no ADSes exist.</returns> 241 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] 242 public static IList<string> GetADSes(this FileInfo info) 243 { 244 List<string> result = new List<string>(); 245 using (FileStream stream = new StreamInfo(info.FullName).Open(FileMode.Open, 246 FileAccess.Read, FileShare.ReadWrite)) 247 using (SafeFileHandle streamHandle = stream.SafeFileHandle) 248 { 249 //Allocate the structures 250 NativeMethods.FILE_STREAM_INFORMATION[] streams = GetADSes(streamHandle); 251 252 foreach (NativeMethods.FILE_STREAM_INFORMATION streamInfo in streams) 253 { 254 //Get the name of the stream. The raw value is :NAME:$DATA 255 string streamName = streamInfo.StreamName.Substring(1, 256 streamInfo.StreamName.LastIndexOf(':') - 1); 257 258 if (streamName.Length != 0) 259 result.Add(streamName); 260 } 261 } 262 263 return result.AsReadOnly(); 264 } 265 266 private static NativeMethods.FILE_STREAM_INFORMATION[] GetADSes(SafeFileHandle FileHandle) 267 { 268 NativeMethods.IO_STATUS_BLOCK status = new NativeMethods.IO_STATUS_BLOCK(); 269 IntPtr fileInfoPtr = IntPtr.Zero; 270 271 try 272 { 273 NativeMethods.FILE_STREAM_INFORMATION streamInfo = 274 new NativeMethods.FILE_STREAM_INFORMATION(); 275 int fileInfoPtrLength = (Marshal.SizeOf(streamInfo) + 32768) / 2; 276 uint ntStatus = 0; 277 278 do 279 { 280 fileInfoPtrLength *= 2; 281 if (fileInfoPtr != IntPtr.Zero) 282 Marshal.FreeHGlobal(fileInfoPtr); 283 fileInfoPtr = Marshal.AllocHGlobal(fileInfoPtrLength); 284 285 ntStatus = NativeMethods.NtQueryInformationFile(FileHandle, ref status, 286 fileInfoPtr, (uint)fileInfoPtrLength, 287 NativeMethods.FILE_INFORMATION_CLASS.FileStreamInformation); 288 } 289 while (ntStatus != 0 /*STATUS_SUCCESS*/ && ntStatus == 0x80000005 /*STATUS_BUFFER_OVERFLOW*/); 290 291 //Marshal the structure manually (argh!) 292 List<NativeMethods.FILE_STREAM_INFORMATION> result = 293 new List<NativeMethods.FILE_STREAM_INFORMATION>(); 294 unsafe 295 { 296 for (byte* i = (byte*)fileInfoPtr; streamInfo.NextEntryOffset != 0; 297 i += streamInfo.NextEntryOffset) 298 { 299 byte* currStreamPtr = i; 300 streamInfo.NextEntryOffset = *(uint*)currStreamPtr; 301 currStreamPtr += sizeof(uint); 302 303 streamInfo.StreamNameLength = *(uint*)currStreamPtr; 304 currStreamPtr += sizeof(uint); 305 306 streamInfo.StreamSize = *(long*)currStreamPtr; 307 currStreamPtr += sizeof(long); 308 309 streamInfo.StreamAllocationSize = *(long*)currStreamPtr; 310 currStreamPtr += sizeof(long); 311 312 streamInfo.StreamName = Marshal.PtrToStringUni((IntPtr)currStreamPtr, 313 (int)streamInfo.StreamNameLength / 2); 314 result.Add(streamInfo); 315 } 316 } 317 318 return result.ToArray(); 319 } 320 finally 321 { 322 Marshal.FreeHGlobal(fileInfoPtr); 323 } 324 } 76 325 } 77 326 } -
branches/eraser6/CodeReview/Eraser.Util/FileSize.cs
r1705 r1709 1 /*1 /* 2 2 * $Id$ 3 3 * Copyright 2008-2010 The Eraser Project 4 4 * Original Author: Joel Low <lowjoel@users.sourceforge.net> 5 * Modified By: Kasra Nassiri <cjax@users.sourceforge.net> @10/7/20085 * Modified By: 6 6 * 7 7 * This file is part of Eraser. … … 24 24 using System.Text; 25 25 26 using System.Runtime.InteropServices;27 using System.ComponentModel;28 using System.Windows.Forms;29 using System.Drawing;30 using System.IO;31 using Microsoft.Win32.SafeHandles;32 26 using System.Globalization; 33 27 34 28 namespace Eraser.Util 35 29 { 36 public static class File 30 /// <summary> 31 /// Gets the human-readable representation of a file size from the byte-wise 32 /// length of a file. This returns a KB = 1024 bytes (Windows convention.) 33 /// </summary> 34 public struct FileSize : IConvertible 37 35 { 38 36 /// <summary> 39 /// Gets the list of ADSes of the given file.37 /// Constructor. 40 38 /// </summary> 41 /// <param name="info">The FileInfo object with the file path etc.</param> 42 /// <returns>A list containing the names of the ADSes of each file. The 43 /// list will be empty if no ADSes exist.</returns> 44 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] 45 public static IList<string> GetADSes(FileInfo info) 39 /// <param name="filesize">The size of the file, in bytes.</param> 40 public FileSize(long filesize) 41 : this() 46 42 { 47 List<string> result = new List<string>(); 48 using (FileStream stream = new StreamInfo(info.FullName).Open(FileMode.Open, 49 FileAccess.Read, FileShare.ReadWrite)) 50 using (SafeFileHandle streamHandle = stream.SafeFileHandle) 51 { 52 //Allocate the structures 53 NativeMethods.FILE_STREAM_INFORMATION[] streams = GetADSes(streamHandle); 54 55 foreach (NativeMethods.FILE_STREAM_INFORMATION streamInfo in streams) 56 { 57 //Get the name of the stream. The raw value is :NAME:$DATA 58 string streamName = streamInfo.StreamName.Substring(1, 59 streamInfo.StreamName.LastIndexOf(':') - 1); 60 61 if (streamName.Length != 0) 62 result.Add(streamName); 63 } 64 } 65 66 return result.AsReadOnly(); 43 Size = filesize; 67 44 } 68 45 69 private static NativeMethods.FILE_STREAM_INFORMATION[] GetADSes(SafeFileHandle FileHandle) 46 #region IConvertible Members 47 48 public TypeCode GetTypeCode() 70 49 { 71 NativeMethods.IO_STATUS_BLOCK status = new NativeMethods.IO_STATUS_BLOCK();72 IntPtr fileInfoPtr = IntPtr.Zero;50 return TypeCode.Int64; 51 } 73 52 74 try 75 { 76 NativeMethods.FILE_STREAM_INFORMATION streamInfo = 77 new NativeMethods.FILE_STREAM_INFORMATION(); 78 int fileInfoPtrLength = (Marshal.SizeOf(streamInfo) + 32768) / 2; 79 uint ntStatus = 0; 53 public bool ToBoolean(IFormatProvider provider) 54 { 55 throw new InvalidCastException(); 56 } 80 57 81 do 82 { 83 fileInfoPtrLength *= 2; 84 if (fileInfoPtr != IntPtr.Zero) 85 Marshal.FreeHGlobal(fileInfoPtr); 86 fileInfoPtr = Marshal.AllocHGlobal(fileInfoPtrLength); 58 public byte ToByte(IFormatProvider provider) 59 { 60 return Convert.ToByte(Size); 61 } 87 62 88 ntStatus = NativeMethods.NtQueryInformationFile(FileHandle, ref status, 89 fileInfoPtr, (uint)fileInfoPtrLength, 90 NativeMethods.FILE_INFORMATION_CLASS.FileStreamInformation); 91 } 92 while (ntStatus != 0 /*STATUS_SUCCESS*/ && ntStatus == 0x80000005 /*STATUS_BUFFER_OVERFLOW*/); 63 public char ToChar(IFormatProvider provider) 64 { 65 throw new InvalidCastException(); 66 } 93 67 94 //Marshal the structure manually (argh!) 95 List<NativeMethods.FILE_STREAM_INFORMATION> result = 96 new List<NativeMethods.FILE_STREAM_INFORMATION>(); 97 unsafe 98 { 99 for (byte* i = (byte*)fileInfoPtr; streamInfo.NextEntryOffset != 0; 100 i += streamInfo.NextEntryOffset) 101 { 102 byte* currStreamPtr = i; 103 streamInfo.NextEntryOffset = *(uint*)currStreamPtr; 104 currStreamPtr += sizeof(uint); 68 public DateTime ToDateTime(IFormatProvider provider) 69 { 70 throw new InvalidCastException(); 71 } 105 72 106 streamInfo.StreamNameLength = *(uint*)currStreamPtr; 107 currStreamPtr += sizeof(uint); 73 public decimal ToDecimal(IFormatProvider provider) 74 { 75 return Convert.ToDecimal(Size); 76 } 108 77 109 streamInfo.StreamSize = *(long*)currStreamPtr; 110 currStreamPtr += sizeof(long); 78 public double ToDouble(IFormatProvider provider) 79 { 80 return Convert.ToDouble(Size); 81 } 111 82 112 streamInfo.StreamAllocationSize = *(long*)currStreamPtr; 113 currStreamPtr += sizeof(long); 83 public short ToInt16(IFormatProvider provider) 84 { 85 return Convert.ToInt16(Size); 86 } 114 87 115 streamInfo.StreamName = Marshal.PtrToStringUni((IntPtr)currStreamPtr, 116 (int)streamInfo.StreamNameLength / 2); 117 result.Add(streamInfo); 118 } 119 } 88 public int ToInt32(IFormatProvider provider) 89 { 90 return Convert.ToInt32(Size); 91 } 120 92 121 return result.ToArray(); 122 } 123 finally 124 { 125 Marshal.FreeHGlobal(fileInfoPtr); 126 } 93 public long ToInt64(IFormatProvider provider) 94 { 95 return Size; 96 } 97 98 public sbyte ToSByte(IFormatProvider provider) 99 { 100 return Convert.ToSByte(Size); 101 } 102 103 public float ToSingle(IFormatProvider provider) 104 { 105 return Convert.ToSingle(Size); 106 } 107 108 public string ToString(IFormatProvider provider) 109 { 110 return ToString(Size); 111 } 112 113 public object ToType(Type conversionType, IFormatProvider provider) 114 { 115 return Convert.ChangeType(Size, conversionType, provider); 116 } 117 118 public ushort ToUInt16(IFormatProvider provider) 119 { 120 return Convert.ToUInt16(Size); 121 } 122 123 public uint ToUInt32(IFormatProvider provider) 124 { 125 return Convert.ToUInt32(Size); 126 } 127 128 public ulong ToUInt64(IFormatProvider provider) 129 { 130 return Convert.ToUInt64(Size); 131 } 132 133 #endregion 134 135 /// <summary> 136 /// The size of the file, in bytes. 137 /// </summary> 138 public long Size 139 { 140 get; 141 private set; 127 142 } 128 143 129 144 /// <summary> 130 /// Uses SHGetFileInfo to retrieve the description for the given file, 131 /// folder or drive. 145 /// Converts this file size to the concise equivalent. 132 146 /// </summary> 133 /// <param name="path">A string that contains the path and file name for 134 /// the file in question. Both absolute and relative paths are valid. 135 /// Directories and volumes must contain the trailing \</param> 136 /// <returns>A string containing the description</returns> 137 public static string GetFileDescription(string path) 147 /// <returns>A string containing the file size and the associated unit. 148 /// Files larger than 1MB will be accurate to 2 decimal places.</returns> 149 public override string ToString() 138 150 { 139 NativeMethods.SHFILEINFO shfi = new NativeMethods.SHFILEINFO(); 140 NativeMethods.SHGetFileInfo(path, 0, ref shfi, Marshal.SizeOf(shfi), 141 NativeMethods.SHGetFileInfoFlags.SHGFI_DISPLAYNAME); 142 return shfi.szDisplayName; 151 return ToString(CultureInfo.CurrentCulture); 143 152 } 144 153 145 154 /// <summary> 146 /// Uses SHGetFileInfo to retrieve the icon for the given file, folder or 147 /// drive. 155 /// Converts a file size to the concise equivalent. 148 156 /// </summary> 149 /// <param name="path">A string that contains the path and file name for 150 /// the file in question. Both absolute and relative paths are valid. 151 /// Directories and volumes must contain the trailing \</param> 152 /// <returns>An Icon object containing the bitmap</returns> 153 public static Icon GetFileIcon(string path) 154 { 155 NativeMethods.SHFILEINFO shfi = new NativeMethods.SHFILEINFO(); 156 NativeMethods.SHGetFileInfo(path, 0, ref shfi, Marshal.SizeOf(shfi), 157 NativeMethods.SHGetFileInfoFlags.SHGFI_SMALLICON | 158 NativeMethods.SHGetFileInfoFlags.SHGFI_ICON); 159 160 if (shfi.hIcon != IntPtr.Zero) 161 return Icon.FromHandle(shfi.hIcon); 162 else 163 throw new IOException(string.Format(CultureInfo.CurrentCulture, 164 "Could not load file icon from {0}", path), 165 Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error())); 166 } 167 168 /// <summary> 169 /// Compacts the file path, fitting in the given width. 170 /// </summary> 171 /// <param name="longPath">The long file path.</param> 172 /// <param name="newWidth">The target width of the text.</param> 173 /// <param name="drawFont">The font used for drawing the text.</param> 174 /// <returns>The compacted file path.</returns> 175 public static string GetCompactPath(string longPath, int newWidth, Font drawFont) 176 { 177 using (Control ctrl = new Control()) 178 { 179 //First check if the source string is too long. 180 Graphics g = ctrl.CreateGraphics(); 181 int width = g.MeasureString(longPath, drawFont).ToSize().Width; 182 if (width <= newWidth) 183 return longPath; 184 185 //It is, shorten it. 186 int aveCharWidth = width / longPath.Length; 187 int charCount = newWidth / aveCharWidth; 188 StringBuilder builder = new StringBuilder(); 189 builder.Append(longPath); 190 builder.EnsureCapacity(charCount); 191 192 while (g.MeasureString(builder.ToString(), drawFont).Width > newWidth) 193 { 194 if (!NativeMethods.PathCompactPathEx(builder, longPath, 195 (uint)charCount--, 0)) 196 { 197 return string.Empty; 198 } 199 } 200 201 return builder.ToString(); 202 } 203 } 204 205 /// <summary> 206 /// Determines if a given file is protected by SFC. 207 /// </summary> 208 /// <param name="filePath">The path to check</param> 209 /// <returns>True if the file is protected.</returns> 210 public static bool IsProtectedSystemFile(string filePath) 211 { 212 return NativeMethods.SfcIsFileProtected(IntPtr.Zero, filePath); 213 } 214 215 /// <summary> 216 /// Checks whether the path given is compressed. 217 /// </summary> 218 /// <param name="path">The path to the file or folder</param> 219 /// <returns>True if the file or folder is compressed.</returns> 220 public static bool IsCompressed(string path) 221 { 222 ushort compressionStatus = 0; 223 uint bytesReturned = 0; 224 225 using (SafeFileHandle handle = NativeMethods.CreateFile(path, 226 NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 227 0, IntPtr.Zero, NativeMethods.OPEN_EXISTING, 228 NativeMethods.FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero)) 229 { 230 if (NativeMethods.DeviceIoControl(handle, NativeMethods.FSCTL_GET_COMPRESSION, 231 IntPtr.Zero, 0, out compressionStatus, sizeof(ushort), out bytesReturned, 232 IntPtr.Zero)) 233 { 234 return compressionStatus != NativeMethods.COMPRESSION_FORMAT_NONE; 235 } 236 } 237 238 return false; 239 } 240 241 /// <summary> 242 /// Sets whether the file system object pointed to by path is compressed. 243 /// </summary> 244 /// <param name="path">The path to the file or folder.</param> 245 /// <returns>True if the file or folder has its compression value set.</returns> 246 public static bool SetCompression(string path, bool compressed) 247 { 248 ushort compressionStatus = compressed ? 249 NativeMethods.COMPRESSION_FORMAT_DEFAULT : 250 NativeMethods.COMPRESSION_FORMAT_NONE; 251 uint bytesReturned = 0; 252 253 using (SafeFileHandle handle = NativeMethods.CreateFile(path, 254 NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 255 0, IntPtr.Zero, NativeMethods.OPEN_EXISTING, 256 NativeMethods.FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero)) 257 { 258 return NativeMethods.DeviceIoControl(handle, NativeMethods.FSCTL_SET_COMPRESSION, 259 ref compressionStatus, sizeof(ushort), IntPtr.Zero, 0, out bytesReturned, 260 IntPtr.Zero); 261 } 262 } 263 264 /// <summary> 265 /// Gets the human-readable representation of a file size from the byte-wise 266 /// length of a file. This returns a KB = 1024 bytes (Windows convention.) 267 /// </summary> 268 /// <param name="bytes">The file size to scale.</param> 157 /// <param name="size">The size of the file to convert.</param> 269 158 /// <returns>A string containing the file size and the associated unit. 270 159 /// Files larger than 1MB will be accurate to 2 decimal places.</returns> 271 public static string GetHumanReadableFileSize(long bytes)160 public static string ToString(long size) 272 161 { 273 162 //List of units, in ascending scale … … 282 171 }; 283 172 284 double d Bytes = (double)bytes;173 double dSize = (double)size; 285 174 for (int i = 0; i != units.Length; ++i) 286 175 { 287 if (d Bytes< 1000.0)176 if (dSize < 1000.0) 288 177 if (i <= 1) 289 178 return string.Format(CultureInfo.CurrentCulture, 290 "{0} {1}", (int)d Bytes, units[i]);179 "{0} {1}", (int)dSize, units[i]); 291 180 else 292 181 return string.Format(CultureInfo.CurrentCulture, 293 "{0:0.00} {1}", d Bytes, units[i]);294 d Bytes/= 1024.0;182 "{0:0.00} {1}", dSize, units[i]); 183 dSize /= 1024.0; 295 184 } 296 185 297 186 return string.Format(CultureInfo.CurrentCulture, "{0, 2} {1}", 298 dBytes, units[units.Length - 1]); 299 } 300 301 private static DateTime FileTimeToDateTime(System.Runtime.InteropServices.ComTypes.FILETIME value) 302 { 303 long time = (long)((((ulong)value.dwHighDateTime) << sizeof(int) * 8) | 304 (uint)value.dwLowDateTime); 305 return DateTime.FromFileTime(time); 306 } 307 308 private static System.Runtime.InteropServices.ComTypes.FILETIME DateTimeToFileTime(DateTime value) 309 { 310 long time = value.ToFileTime(); 311 312 System.Runtime.InteropServices.ComTypes.FILETIME result = 313 new System.Runtime.InteropServices.ComTypes.FILETIME(); 314 result.dwLowDateTime = (int)(time & 0xFFFFFFFFL); 315 result.dwHighDateTime = (int)(time >> 32); 316 317 return result; 318 } 319 320 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] 321 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")] 322 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "3#")] 323 public static void GetFileTime(SafeFileHandle file, out DateTime creationTime, 324 out DateTime accessedTime, out DateTime modifiedTime) 325 { 326 System.Runtime.InteropServices.ComTypes.FILETIME accessedTimeNative = 327 new System.Runtime.InteropServices.ComTypes.FILETIME(); 328 System.Runtime.InteropServices.ComTypes.FILETIME modifiedTimeNative = 329 new System.Runtime.InteropServices.ComTypes.FILETIME(); 330 System.Runtime.InteropServices.ComTypes.FILETIME createdTimeNative = 331 new System.Runtime.InteropServices.ComTypes.FILETIME(); 332 333 if (!NativeMethods.GetFileTime(file, out createdTimeNative, out accessedTimeNative, 334 out modifiedTimeNative)) 335 { 336 throw Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); 337 } 338 339 creationTime = FileTimeToDateTime(createdTimeNative); 340 accessedTime = FileTimeToDateTime(accessedTimeNative); 341 modifiedTime = FileTimeToDateTime(modifiedTimeNative); 342 } 343 344 public static void SetFileTime(SafeFileHandle file, DateTime creationTime, 345 DateTime accessedTime, DateTime modifiedTime) 346 { 347 System.Runtime.InteropServices.ComTypes.FILETIME accessedTimeNative = 348 new System.Runtime.InteropServices.ComTypes.FILETIME(); 349 System.Runtime.InteropServices.ComTypes.FILETIME modifiedTimeNative = 350 new System.Runtime.InteropServices.ComTypes.FILETIME(); 351 System.Runtime.InteropServices.ComTypes.FILETIME createdTimeNative = 352 new System.Runtime.InteropServices.ComTypes.FILETIME(); 353 354 if (!NativeMethods.GetFileTime(file, out createdTimeNative, 355 out accessedTimeNative, out modifiedTimeNative)) 356 { 357 throw Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); 358 } 359 360 if (creationTime != DateTime.MinValue) 361 createdTimeNative = DateTimeToFileTime(creationTime); 362 if (accessedTime != DateTime.MinValue) 363 accessedTimeNative = DateTimeToFileTime(accessedTime); 364 if (modifiedTime != DateTime.MinValue) 365 modifiedTimeNative = DateTimeToFileTime(modifiedTime); 366 367 if (!NativeMethods.SetFileTime(file, ref createdTimeNative, 368 ref accessedTimeNative, ref modifiedTimeNative)) 369 { 370 throw Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); 371 } 187 dSize, units[units.Length - 1]); 372 188 } 373 189 } -
branches/eraser6/CodeReview/Eraser.Util/Localisation.cs
r1681 r1709 153 153 public static bool LocalisationExists(CultureInfo culture, Assembly assembly) 154 154 { 155 return System.IO.File.Exists(Path.Combine(155 return File.Exists(Path.Combine( 156 156 Path.Combine(Path.GetDirectoryName(assembly.Location), culture.Name), //Directory 157 157 Path.GetFileNameWithoutExtension(assembly.Location) + ".resources.dll")); … … 194 194 { 195 195 path = Path.Combine(Path.GetDirectoryName(assembly.Location), culture.Name); 196 if ( System.IO.Directory.Exists(path))196 if (Directory.Exists(path)) 197 197 { 198 198 string assemblyPath = Path.Combine(path, 199 199 Path.GetFileNameWithoutExtension(assembly.Location) + ".resources.dll"); 200 if ( System.IO.File.Exists(assemblyPath))200 if (File.Exists(assemblyPath)) 201 201 { 202 202 languageID = culture.Name; -
branches/eraser6/CodeReview/Eraser/Program.cs
r1623 r1709 39 39 using Eraser.Manager; 40 40 using Eraser.Util; 41 using File = System.IO.File;42 41 43 42 namespace Eraser … … 522 521 catch (SerializationException ex) 523 522 { 524 System.IO.File.Delete(TaskListPath);523 File.Delete(TaskListPath); 525 524 MessageBox.Show(S._("Could not load task list. All task entries have " + 526 525 "been lost. The error returned was: {0}", ex.Message), S._("Eraser"), -
branches/eraser6/CodeReview/Eraser/TaskDataSelectionForm.cs
r1681 r1709 30 30 using Eraser.Manager; 31 31 using Eraser.Util; 32 using Eraser.Util.ExtensionMethods; 32 33 using System.IO; 33 34 … … 70 71 DriveItem item = new DriveItem(); 71 72 string volumePath = volume.MountPoints[0]; 73 DirectoryInfo root = new DirectoryInfo(volumePath); 74 72 75 item.Drive = volumePath; 73 item.Label = Eraser.Util.File.GetFileDescription(volumePath);74 item.Icon = Eraser.Util.File.GetFileIcon(volumePath);76 item.Label = root.GetDescription(); 77 item.Icon = root.GetIcon(); 75 78 unusedDisk.Items.Add(item); 76 79 } -
branches/eraser6/CodeReview/Eraser/UpdateForm.cs
r1701 r1709 193 193 item.SubItems.Add(update.Version.ToString()); 194 194 item.SubItems.Add(update.Publisher); 195 item.SubItems.Add( Util.File.GetHumanReadableFileSize(update.FileSize));195 item.SubItems.Add(FileSize.ToString(update.FileSize)); 196 196 197 197 item.Tag = update; … … 330 330 update.amountDownloaded = (long)(e.ProgressPercentage * update.Update.FileSize); 331 331 update.LVItem.ImageIndex = 0; 332 update.LVItem.SubItems[1].Text = Util.File.GetHumanReadableFileSize(332 update.LVItem.SubItems[1].Text = FileSize.ToString( 333 333 update.Update.FileSize - update.amountDownloaded); 334 334 } … … 343 343 amountToDownload += upd.Update.FileSize - upd.amountDownloaded; 344 344 downloadingOverallLbl.Text = S._("Overall progress: {0} left", 345 Util.File.GetHumanReadableFileSize(amountToDownload));345 FileSize.ToString(amountToDownload)); 346 346 } 347 347 … … 554 554 OnProgress(new ProgressEventArgs(progress.Progress, progress.Progress, null, 555 555 S._("{0} of {1} downloaded", 556 Util.File.GetHumanReadableFileSize(progress.Completed),557 Util.File.GetHumanReadableFileSize(progress.Total))));556 FileSize.ToString(progress.Completed), 557 FileSize.ToString(progress.Total)))); 558 558 } 559 559
Note: See TracChangeset
for help on using the changeset viewer.
