1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity
{
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Threading;
/// <summary>
/// This class provides utility methods for common I/O tasks not directly supported by .NET Framework BCL,
/// as well as I/O tasks that require elevated privileges.
/// </summary>
public static class IOHelpers
{
private const int DefaultCopyBufferSize = 65536;
#if !SILVERLIGHT
/// <summary>
/// Safely determines whether the given path refers to an existing directory on disk.
/// </summary>
/// <param name="path"> The path to test. </param>
/// <returns> True if path refers to an existing directory; otherwise, false. </returns>
[SecuritySafeCritical]
// Calling Directory.Exists demands FileIOPermission (Read flag) for the specified path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
public static bool DirectoryExists(string path)
{
return Directory.Exists(path);
}
/// <summary>
/// Creates the specified directory if it doesn't exist or removes all contents of an existing directory.
/// </summary>
/// <param name="path"> Path to directory to create. </param>
[SecuritySafeCritical]
// Calling Directory.Exists demands FileIOPermission (Read flag) for the specified path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
public static void EnsureDirectoryEmpty(string path)
{
if (Directory.Exists(path))
{
SafeDeleteDirectory(path);
}
EnsureDirectoryExists(path);
}
/// <summary>
/// Creates the specified directory if it doesn't exist.
/// </summary>
/// <param name="path"> Path to directory to create. </param>
[SecuritySafeCritical]
// Calling Directory.Exists and Directory.CreateDirectory demands FileIOPermission (Read | Write) for the specified path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
public static void EnsureDirectoryExists(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/// <summary>
/// Safely determines whether the specified file exists.
/// </summary>
/// <param name="path"> The file to check. </param>
/// <returns> True if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path. </returns>
[SecuritySafeCritical]
// Calling File.Exists demands FileIOPermission (Read flag) for the specified path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
public static bool FileExists(string path)
{
return File.Exists(path);
}
/// <summary>
/// Safely returns the absolute path for the specified path string.
/// </summary>
/// <param name="path"> The file or directory for which to obtain absolute path information. </param>
/// <returns> A string containing the fully qualified location of path, such as "C:\MyFile.txt". </returns>
[SecuritySafeCritical]
// Calling Path.GetFullPath demands FileIOPermission (PathDiscovery flag) for the specified path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
public static string GetFullPath(string path)
{
return Path.GetFullPath(path);
}
/// <summary>
/// Safely deletes the file and ignores any access violation exceptions.
/// </summary>
/// <param name="path"> The directory to delete. </param>
[SecuritySafeCritical]
// Calling File.Delete demands FileIOPermission (Write flag) for the specified path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Need to catch everything here.")]
public static void SafeDeleteFile(string path)
{
try
{
File.Delete(path);
}
catch (Exception)
{
// ignore exceptions
}
}
/// <summary>
/// Safely deletes the directory and ignores any access violation exceptions.
/// </summary>
/// <param name="path"> The directory to delete. </param>
[SecuritySafeCritical]
// Calling Directory.Delete demands FileIOPermission (Write flag) for the specified path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Need to catch everything here.")]
public static void SafeDeleteDirectory(string path)
{
// try different ways of contents of directory, fail after 3 attempts
for (var i = 0; i < 3; ++i)
{
try
{
Directory.Delete(path, true);
return;
}
catch (Exception)
{
}
Thread.Sleep(500);
try
{
foreach (var file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
{
SafeDeleteFile(file);
}
return;
}
catch (Exception)
{
}
Thread.Sleep(500);
}
}
/// <summary>
/// Creates a uniquely named, empty temporary directory on disk and returns the
/// full path of that directory.
/// </summary>
/// <returns> A <see cref="String" /> containing the full path of the temporary directory. </returns>
public static string GetTempDirName()
{
var tempDir = Path.GetTempFileName();
File.Delete(tempDir);
Directory.CreateDirectory(tempDir);
return tempDir;
}
/// <summary>
/// Copies the specified source files to a given directory.
/// </summary>
/// <param name="destinationDirectory"> The destination directory. </param>
/// <param name="sourceFiles"> The source files. </param>
[SecuritySafeCritical]
// Calling File.Copy demands FileIOPermission (Write flag) for the destination file path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
public static void CopyToDirectory(string destinationDirectory, params string[] sourceFiles)
{
foreach (var sourceFile in sourceFiles)
{
var baseName = Path.GetFileName(sourceFile);
var destinationFile = Path.Combine(destinationDirectory, baseName);
if (new FileInfo(sourceFile).FullName
!= new FileInfo(destinationFile).FullName)
{
File.Copy(sourceFile, destinationFile, true);
}
}
}
#endif
public static void CopyToDir(string sourceFileName, string destDirName)
{
File.Copy(
sourceFileName,
Path.Combine(
destDirName,
Path.GetFileName(sourceFileName)));
}
/// <summary>
/// Copies contents of one stream into another.
/// </summary>
/// <param name="source"> Stream to read from. </param>
/// <param name="destination"> Stream to write to. </param>
/// <returns> The number of bytes copied from the source. </returns>
public static int CopyStream(Stream source, Stream destination)
{
return CopyStream(source, destination, new byte[DefaultCopyBufferSize]);
}
/// <summary>
/// Copies contents of one stream into another.
/// </summary>
/// <param name="source"> Stream to read from. </param>
/// <param name="destination"> Stream to write to. </param>
/// <param name="copyBuffer"> The copy buffer. </param>
/// <returns> The number of bytes copied from the source. </returns>
public static int CopyStream(Stream source, Stream destination, byte[] copyBuffer)
{
ExceptionHelpers.CheckArgumentNotNull(source, "source");
ExceptionHelpers.CheckArgumentNotNull(destination, "destination");
ExceptionHelpers.CheckArgumentNotNull(copyBuffer, "copyBuffer");
var bytesCopied = 0;
int bytesRead;
do
{
bytesRead = source.Read(copyBuffer, 0, copyBuffer.Length);
destination.Write(copyBuffer, 0, bytesRead);
bytesCopied += bytesRead;
}
while (bytesRead != 0);
return bytesCopied;
}
/// <summary>
/// Write an embedded resource to a local file
/// </summary>
/// <param name="resourceName"> Resource to be written </param>
/// <param name="fileName"> File to write resource to </param>
/// <param name="assembly"> Assembly to extract resource from </param>
#if !SILVERLIGHT
[SecuritySafeCritical]
// Calling File.Open demands FileIOPermission (Append flag) for the destination file path.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
#endif
public static void WriteResourceToFile(string resourceName, string fileName, Assembly assembly)
{
using (var resourceStream = assembly.GetManifestResourceStream(resourceName))
{
if (resourceStream == null)
{
throw new IOException("Resource '" + resourceName + "' not found in '" + assembly.FullName + "'");
}
using (var fileStream = File.Open(fileName, FileMode.Append))
{
CopyStream(resourceStream, fileStream);
}
}
}
#if !SILVERLIGHT
/// <summary>
/// Adds the given set of file attributes to the file at the given path
/// </summary>
/// <param name="fileName"> The name/path of the file </param>
/// <param name="toAdd"> The bit-field of attributes to add </param>
public static void AddFileAttributes(string fileName, FileAttributes toAdd)
{
File.SetAttributes(fileName, File.GetAttributes(fileName) | toAdd);
}
/// <summary>
/// Removes the given set of file attributes from the file at the given path
/// </summary>
/// <param name="fileName"> The name/path of the file </param>
/// <param name="toRemove"> The bit-field of attributes to remove </param>
public static void RemoveFileAttributes(string fileName, FileAttributes toRemove)
{
File.SetAttributes(fileName, File.GetAttributes(fileName) & ~toRemove);
}
#endif
}
}
|