private void DumpCopy(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); string path = isLocal ? SysRoot : Path.LocalToUnc(SysRoot); string tempPath = Path.GetTempPath("File-Copy-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); bool exception; int expectedLastError; string expectedException; string fileSource = @"file-source-" + Path.GetRandomFileName() + ".exe"; string fileDestination = @"file-destination-" + Path.GetRandomFileName() + ".exe"; string folderSource = tempPath + @"\folder-source-" + Path.GetRandomFileName(); string folderDestination = tempPath + @"\folder-destination-" + Path.GetRandomFileName(); string fullPathSource = folderSource + @"\" + fileSource; string fullPathDestination = folderDestination + @"\" + fileDestination; if (!isLocal) fullPathSource = Path.LocalToUnc(fullPathSource); if (!isLocal) fullPathDestination = Path.LocalToUnc(fullPathDestination); DirectoryInfo dirInfo = new DirectoryInfo(folderDestination); #endregion // Setup try { #region UnauthorizedAccessException Directory.CreateDirectory(folderSource); Directory.CreateDirectory(folderDestination); DirectorySecurity dirSecurity; string user = (Environment.UserDomainName + @"\" + Environment.UserName).TrimStart('\\'); // ╔═════════════╦═════════════╦═══════════════════════════════╦════════════════════════╦══════════════════╦═══════════════════════╦═════════════╦═════════════╗ // ║ ║ folder only ║ folder, sub-folders and files ║ folder and sub-folders ║ folder and files ║ sub-folders and files ║ sub-folders ║ files ║ // ╠═════════════╬═════════════╬═══════════════════════════════╬════════════════════════╬══════════════════╬═══════════════════════╬═════════════╬═════════════╣ // ║ Propagation ║ none ║ none ║ none ║ none ║ InheritOnly ║ InheritOnly ║ InheritOnly ║ // ║ Inheritance ║ none ║ Container|Object ║ Container ║ Object ║ Container|Object ║ Container ║ Object ║ // ╚═════════════╩═════════════╩═══════════════════════════════╩════════════════════════╩══════════════════╩═══════════════════════╩═════════════╩═════════════╝ var rule = new FileSystemAccessRule(user, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny); expectedLastError = (int)Win32Errors.ERROR_ACCESS_DENIED; expectedException = "System.UnauthorizedAccessException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: The caller does not have the required permission.", expectedException); FileInfo fileInfo = new FileInfo(fullPathSource); using (StreamWriter sw = fileInfo.CreateText()) sw.WriteLine("MoveTo-TestFile"); // Set DENY for current user. dirSecurity = dirInfo.GetAccessControl(); dirSecurity.AddAccessRule(rule); dirInfo.SetAccessControl(dirSecurity); fileInfo.CopyTo(fullPathDestination); } catch (UnauthorizedAccessException ex) { Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError)); exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } finally { // Remove DENY for current user. dirSecurity = dirInfo.GetAccessControl(); dirSecurity.RemoveAccessRule(rule); dirInfo.SetAccessControl(dirSecurity, AccessControlSections.Access); Directory.Delete(tempPath, true, true); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // UnauthorizedAccessException #region FileNotFoundException expectedLastError = (int)Win32Errors.ERROR_FILE_NOT_FOUND; expectedException = "System.IO.FileNotFoundException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: sourceFileName was not found.", expectedException); File.Copy(isLocal ? fileSource : Path.LocalToUnc(fileSource), isLocal ? fileDestination : Path.LocalToUnc(fileDestination)); } catch (FileNotFoundException ex) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // FileNotFoundException #region DirectoryNotFoundException expectedLastError = (int)Win32Errors.ERROR_PATH_NOT_FOUND; expectedException = "System.IO.DirectoryNotFoundException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: The path specified in sourceFileName or destFileName is invalid (for example, it is on an unmapped drive).", expectedException); File.Copy(fullPathSource, fullPathDestination); } catch (DirectoryNotFoundException ex) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // DirectoryNotFoundException #region IOException #1 (AlreadyExistsException) Directory.CreateDirectory(folderSource); Directory.CreateDirectory(folderDestination); using (File.Create(fullPathSource)) { } using (File.Create(fullPathDestination)) { } expectedLastError = (int)Win32Errors.ERROR_FILE_EXISTS; expectedException = "System.IO.IOException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: destFileName exists and overwrite is false.", expectedException); File.Copy(fullPathSource, fullPathDestination); } catch (AlreadyExistsException ex) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); Directory.Delete(folderSource, true); Directory.Delete(folderDestination, true); #endregion // IOException #1 (AlreadyExistsException) #region IOException #2 string folderfileName = null; expectedLastError = (int)Win32Errors.ERROR_ACCESS_DENIED; expectedException = "System.IO.IOException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: A folder with the same name as the file exists.", expectedException); foreach (string file in Directory.EnumerateFiles(path)) { string newFile = Path.Combine(tempPath, Path.GetFileName(file, true)); folderfileName = newFile; // Trigger the Exception. Directory.CreateDirectory(folderfileName); // true: overwrite existing. File.Copy(file, folderfileName, true); } } catch (AlreadyExistsException ex) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); exception = true; Directory.Delete(folderfileName); Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // IOException #2 #region Copy Console.WriteLine("\nInput Directory Path: [{0}]\n", path); int cnt = 0; string readOnlySource = null; string readOnlyDestination = null; StopWatcher(true); foreach (string file in Directory.EnumerateFiles(path)) { string newFile = Path.Combine(tempPath, Path.GetFileName(file, true)); File.Copy(file, newFile); // Set the first file as read-only to trigger an Exception when copying again. if (cnt == 0) { File.SetAttributes(newFile, FileAttributes.ReadOnly); readOnlySource = file; readOnlyDestination = newFile; } Console.WriteLine("\t#{0:000}\tCopied to: [{1}]", ++cnt, newFile); Assert.IsTrue(File.Exists(newFile)); } Console.WriteLine("\n\tTotal Size: [{0}]{1}", Utils.UnitSizeToText(Directory.GetProperties(tempPath)["Size"]), Reporter()); Console.WriteLine(); #endregion // Copy #region Preserve Timestamps // Test preservation of timestamps. int seed = (int)DateTime.Now.Ticks & 0x0000FFFF; DateTime creationTime = new DateTime(new Random(seed).Next(1971, 2071), new Random(seed).Next(1, 12), new Random(seed).Next(1, 28), new Random(seed).Next(0, 23), new Random(seed).Next(0, 59), new Random(seed).Next(0, 59)); seed += (int)DateTime.Now.Ticks & 0x0000FFFF; DateTime lastAccessTime = new DateTime(new Random(seed).Next(1971, 2071), new Random(seed).Next(1, 12), new Random(seed).Next(1, 28), new Random(seed).Next(0, 23), new Random(seed).Next(0, 59), new Random(seed).Next(0, 59)); seed += (int)DateTime.Now.Ticks & 0x0000FFFF; DateTime lastWriteTime = new DateTime(new Random(seed).Next(1971, 2071), new Random(seed).Next(1, 12), new Random(seed).Next(1, 28), new Random(seed).Next(0, 23), new Random(seed).Next(0, 59), new Random(seed).Next(0, 59)); string preservePath = Path.Combine(tempPath, "PreserveTimestamps"); string preserveFile = Path.GetFileName(readOnlySource); string preserveReadOnlySource = Path.Combine(preservePath, preserveFile); Directory.CreateDirectory(preservePath); File.Copy(readOnlySource, preserveReadOnlySource); File.SetCreationTime(preserveReadOnlySource, creationTime); File.SetLastAccessTime(preserveReadOnlySource, lastAccessTime); File.SetLastWriteTime(preserveReadOnlySource, lastWriteTime); StopWatcher(true); // 3rd parameter CopyOptions.None: overwrite existing. // 4rd parameter true: preserve timestamps of source. File.Copy(preserveReadOnlySource, readOnlyDestination, CopyOptions.None, true); Console.WriteLine("\tFile copied.{0}", Reporter()); Assert.IsTrue(File.Exists(preserveReadOnlySource)); Assert.IsTrue(File.Exists(readOnlyDestination)); Assert.AreEqual(File.GetCreationTime(readOnlyDestination), creationTime, "File CreationTime should match."); Assert.AreEqual(File.GetLastAccessTime(readOnlyDestination), lastAccessTime, "File LastAccessTime should match."); Assert.AreEqual(File.GetLastWriteTime(readOnlyDestination), lastWriteTime, "File LastWriteTime should match."); Console.WriteLine("\nTimestamps are transferred."); #endregion Preserve Timestamps } finally { if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true, true); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } Console.WriteLine(); } }
private void DumpGetSize(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); string tempPath = Path.GetTempPath("File-GetSize()-file-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput File Path: [{0}]\n", tempPath); int randomLines = new Random().Next(1000, 100000); // Create file with contents. FileInfo fi = new FileInfo(tempPath); using (StreamWriter sw = fi.CreateText()) for (int i = 0; i < randomLines; i++) sw.WriteLine(TextHelloWorld); long fileGetSize = File.GetSize(tempPath); long fileGetCompressedSize = File.GetCompressedSize(tempPath); long fiLength = fi.Length; Console.WriteLine("\tFile.GetSize()\t\t\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fileGetSize), fileGetSize); Console.WriteLine("\tFile.GetCompressedSize()\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fileGetCompressedSize), fileGetCompressedSize); Console.WriteLine("\tFileInfo().Length\t\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fiLength), fiLength); Console.WriteLine("\tFileInfo().Attributes\t\t== [{0}]", fi.Attributes); Assert.IsTrue((fi.Attributes & FileAttributes.Compressed) == 0, "File should be uncompressed."); Assert.IsTrue(fiLength == fileGetSize, "Uncompressed size should match."); Assert.IsTrue(fiLength == fileGetCompressedSize, "Uncompressed size should match."); #endregion // Setup #region Compress bool compressOk = false; string report; StopWatcher(true); try { fi.Compress(); report = Reporter(true); compressOk = true; fileGetSize = File.GetSize(tempPath); fileGetCompressedSize = File.GetCompressedSize(tempPath); } catch (Exception ex) { report = Reporter(true); Console.WriteLine("\n\tFile.Compress(): Caught unexpected Exception: [{0}]\n", ex.Message.Replace(Environment.NewLine, " ")); } // FileInfo() must Refresh(). Assert.IsTrue((fi.Attributes & FileAttributes.Compressed) == 0, "FileInfo() should not know it is compressed."); fi.Refresh(); fiLength = fi.Length; Assert.IsTrue((fi.Attributes & FileAttributes.Compressed) != 0, "FileInfo() should know it is compressed."); Console.WriteLine("\n\n\tFile.Compress() (Should be True): [{0}]{1}\n", compressOk, report); Console.WriteLine("\tFile.GetSize()\t\t\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fileGetSize), fileGetSize); Console.WriteLine("\tFile.GetCompressedSize()\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fileGetCompressedSize), fileGetCompressedSize); Console.WriteLine("\tFileInfo().Length\t\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fiLength), fiLength); Console.WriteLine("\tFileInfo().Attributes\t\t== [{0}]", fi.Attributes); Assert.IsTrue(compressOk); Assert.IsTrue((fi.Attributes & FileAttributes.Compressed) != 0, "File should be compressed."); Assert.IsTrue(fiLength != fileGetCompressedSize, "FileInfo() size should not match compressed size."); Assert.IsTrue(fiLength == fileGetSize, "File size should match FileInfo() size."); #endregion // Compress #region Decompress bool decompressOk = false; StopWatcher(true); try { File.Decompress(tempPath); report = Reporter(true); decompressOk = true; fileGetSize = File.GetSize(tempPath); fileGetCompressedSize = File.GetCompressedSize(tempPath); } catch (Exception ex) { report = Reporter(true); Console.WriteLine("\n\tFile.Decompress(): Caught unexpected Exception: [{0}]\n", ex.Message.Replace(Environment.NewLine, " ")); } // FileInfo() must Refresh(). Assert.IsTrue((fi.Attributes & FileAttributes.Compressed) != 0, "FileInfo() should not know it is compressed."); fi.Refresh(); fiLength = fi.Length; Assert.IsTrue((fi.Attributes & FileAttributes.Compressed) == 0, "FileInfo() should know it is compressed."); Console.WriteLine("\n\n\tFile.Decompress() (Should be True): [{0}]{1}\n", decompressOk, report); Console.WriteLine("\tFile.GetSize()\t\t\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fileGetSize), fileGetSize); Console.WriteLine("\tFile.GetCompressedSize()\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fileGetCompressedSize), fileGetCompressedSize); Console.WriteLine("\tFileInfo().Length\t\t== [{0}] [{1} bytes]", Utils.UnitSizeToText(fiLength), fiLength); Console.WriteLine("\tFileInfo().Attributes\t\t== [{0}]", fi.Attributes); Assert.IsTrue(decompressOk); Assert.IsTrue((fi.Attributes & FileAttributes.Compressed) == 0, "File should be uncompressed."); Assert.IsTrue(fiLength == fileGetSize, "Uncompressed size should match."); Assert.IsTrue(fiLength == fileGetCompressedSize, "Uncompressed size should match."); #endregion //Decompress fi.Delete(); fi.Refresh(); // Must Refresh() to get actual state. Assert.IsFalse(fi.Exists, "Cleanup failed: File should have been removed."); Console.WriteLine(); }