private void DumpRefresh(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); string tempPathSysIo = Path.GetTempPath("DirectoryInfo.Refresh()-directory-SysIo-" + Path.GetRandomFileName()); string tempPath = Path.GetTempPath("DirectoryInfo.Refresh()-directory-AlphaFS-" + Path.GetRandomFileName()); if (!isLocal) { tempPathSysIo = Path.LocalToUnc(tempPathSysIo); } if (!isLocal) { tempPath = Path.LocalToUnc(tempPath); } Console.WriteLine("\nInput Directory Path: [{0}]", tempPath); #endregion // Setup #region Refresh try { System.IO.DirectoryInfo diSysIo = new System.IO.DirectoryInfo(tempPathSysIo); DirectoryInfo di = new DirectoryInfo(tempPath); bool existsSysIo = diSysIo.Exists; bool exists = di.Exists; Console.WriteLine("\nnew DirectoryInfo(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Create(); di.Create(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Create(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Delete(); di.Delete(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Delete(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); } finally { if (Directory.Exists(tempPathSysIo)) { Directory.Delete(tempPathSysIo); Assert.IsFalse(Directory.Exists(tempPathSysIo), "Cleanup failed: Directory should have been removed."); } if (Directory.Exists(tempPath)) { Directory.Delete(tempPath); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } Console.WriteLine(); } #endregion // Refresh }
static void CopyWebsiteToTempPath(Path websitePath, Path tempPath) { var originalWebsiteDirectory = new DirectoryInfo(websitePath.FullName); var tempDirectory = new DirectoryInfo(tempPath.FullName); if (tempDirectory.Exists) { Console.WriteLine("Deleting temp directory {0}", tempDirectory.FullName); tempDirectory.Delete(true); } tempDirectory.Refresh(); Console.WriteLine("Creating temp directory {0}", tempDirectory.FullName); tempDirectory.Create(); var bannedExtensionList = new List<string> { ".user", ".cs", ".csproj", ".dotSettings", ".suo", ".xproj", ".targets", ".nuspec", ".orig", ".ncrunchproject" }; var bannedFiles = new List<string> { "packages.config", "project.json", "project.lock.json", "config.json", "bower.json", "package.json", "gruntfile.json", "Microsoft.CodeAnalysis.Analyzers.dll", "Microsoft.CodeAnalysis.VisualBasic.dll", "Microsoft.Build.Tasks.CodeAnalysis.dll", "VBCSCompiler.exe", "web.debug.config", "web.release.config" }; var bannedDirectories = new List<string> {"obj", "node_modules", "bower_components"}; Predicate<FileInfo> bannedExtensions = file => bannedExtensionList.Any( extension => extension.Equals(file.Extension, StringComparison.InvariantCultureIgnoreCase)); Predicate<FileInfo> bannedFileNames = file => bannedFiles.Any( bannedFile => bannedFile.Equals(file.Name, StringComparison.InvariantCultureIgnoreCase)); IEnumerable<Predicate<FileInfo>> filesToExclude = new List<Predicate<FileInfo>> { bannedExtensions, bannedFileNames }; int itemsCopied = originalWebsiteDirectory.CopyTo(tempDirectory, filesToExclude: filesToExclude, directoriesToExclude: bannedDirectories); Console.WriteLine("Copied {0} items", itemsCopied); }
private void DumpRefresh(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); string tempPathSysIo = Path.GetTempPath("DirectoryInfo.Refresh()-directory-SysIo-" + Path.GetRandomFileName()); string tempPath = Path.GetTempPath("DirectoryInfo.Refresh()-directory-AlphaFS-" + Path.GetRandomFileName()); if (!isLocal) tempPathSysIo = Path.LocalToUnc(tempPathSysIo); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput Directory Path: [{0}]", tempPath); #endregion // Setup #region Refresh try { System.IO.DirectoryInfo diSysIo = new System.IO.DirectoryInfo(tempPathSysIo); DirectoryInfo di = new DirectoryInfo(tempPath); bool existsSysIo = diSysIo.Exists; bool exists = di.Exists; Console.WriteLine("\nnew DirectoryInfo(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Create(); di.Create(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Create(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Delete(); di.Delete(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Delete(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); } finally { if (Directory.Exists(tempPathSysIo)) { Directory.Delete(tempPathSysIo); Assert.IsFalse(Directory.Exists(tempPathSysIo), "Cleanup failed: Directory should have been removed."); } if (Directory.Exists(tempPath)) { Directory.Delete(tempPath); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } Console.WriteLine(); } #endregion // Refresh }
private void Directory_EnumerateAlternateDataStreams(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); var tempPath = Path.GetTempPath("Directory-EnumerateAlternateDataStreams-" + Path.GetRandomFileName()); if (isNetwork) { tempPath = Path.LocalToUnc(tempPath); } const int defaultStreamsDirectory = 0; // The default number of data streams for a folder. Console.WriteLine("\nInput Directory Path: [{0}]", tempPath); Console.WriteLine("\nA directory is created and {0} streams are added.", UnitTestConstants.AllStreams.Count()); try { var di = new DirectoryInfo(tempPath); di.Create(); var currentNumberofStreams = di.EnumerateAlternateDataStreams().Count(); Assert.AreEqual(defaultStreamsDirectory, currentNumberofStreams, "Total amount of default streams do not match."); Assert.AreEqual(currentNumberofStreams, Directory.EnumerateAlternateDataStreams(tempPath).Count(), "Total amount of Directory.EnumerateAlternateDataStreams() streams do not match."); Assert.AreEqual(currentNumberofStreams, di.EnumerateAlternateDataStreams().Count(), "Total amount of DirectoryInfo() streams do not match."); // Create alternate data streams. // Because of the colon, you must supply a full path and use PathFormat.FullPath or PathFormat.LongFullPath, // to prevent a: "NotSupportedException: path is in an invalid format." exception. File.WriteAllLines(tempPath + Path.StreamSeparator + UnitTestConstants.MyStream, UnitTestConstants.StreamArrayContent, PathFormat.FullPath); File.WriteAllText(tempPath + Path.StreamSeparator + UnitTestConstants.MyStream2, UnitTestConstants.StreamStringContent, PathFormat.FullPath); var newNumberofStreams = Directory.EnumerateAlternateDataStreams(tempPath).Count(); Console.WriteLine("\n\nCurrent stream Count(): [{0}]", newNumberofStreams); // Enumerate all streams from the folder. foreach (var stream in di.EnumerateAlternateDataStreams()) { Assert.IsTrue(UnitTestConstants.Dump(stream, -10)); } // Show the contents of our streams. Console.WriteLine(); foreach (var streamName in UnitTestConstants.AllStreams) { Console.WriteLine("\n\tStream name: [{0}]", streamName); // Because of the colon, you must supply a full path and use PathFormat.FullPath or PathFormat.LongFullPath, // to prevent a: "NotSupportedException: path is in an invalid format." exception. foreach (var line in File.ReadAllLines(tempPath + Path.StreamSeparator + streamName, PathFormat.FullPath)) { Console.WriteLine("\t\t{0}", line); } } } catch (Exception ex) { Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); Assert.IsTrue(false); } finally { Directory.Delete(tempPath); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } Console.WriteLine(); }
private void DumpCreateDirectory(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); // Directory depth level. int level = new Random().Next(1, 1000); #if NET35 string emspace = "\u3000"; string tempPath = Path.GetTempPath("Directory.CreateDirectory()-" + level + "-" + Path.GetRandomFileName() + emspace); #else // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameter before deleting the directory. string tempPath = Path.GetTempPath("Directory.CreateDirectory()-" + level + "-" + Path.GetRandomFileName()); #endif if (!isLocal) tempPath = Path.LocalToUnc(tempPath); int expectedLastError; string expectedException; string report; bool exist; #endregion // Setup try { #region IOException using (File.Create(tempPath)) { } expectedLastError = (int)Win32Errors.ERROR_ALREADY_EXISTS; expectedException = "System.IO.IOException"; bool exception = false; try { Console.WriteLine("\nCatch: [{0}]: File already exist with same name.", typeof(IOException).FullName); Directory.CreateDirectory(tempPath); } catch (AlreadyExistsException 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, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); File.Delete(tempPath); Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed."); #endregion // IOException #region DirectoryNotFoundException (Local) / IOException (Network) expectedLastError = (int)(isLocal ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_BAD_NET_NAME); expectedException = isLocal ? "System.IO.DirectoryNotFoundException" : "System.IO.IOException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: The specified path is invalid (for example, it is on an unmapped drive).", expectedException); #if NET35 string letter = DriveInfo.GetFreeDriveLetter() + @":\shouldFail" + emspace; #else // MSDN: .NET 4+: Trailing spaces are removed from the end of the path parameter before deleting the directory. string letter = DriveInfo.GetFreeDriveLetter() + @":\Non-Existing"; #endif if (!isLocal) letter = Path.LocalToUnc(letter); Directory.CreateDirectory(letter); } catch (Exception ex) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); string exceptionTypeName = ex.GetType().FullName; if (exceptionTypeName.Equals(expectedException)) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } else Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // DirectoryNotFoundException (Local) / IOException (Network) #region ArgumentException expectedException = "System.ArgumentException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: Path is prefixed with, or contains, only a colon character (:).", expectedException); Directory.CreateDirectory(@":AAAAAAAAAA"); } catch (ArgumentException ex) { 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 // ArgumentException #region NotSupportedException expectedLastError = (int)(isLocal ? Win32Errors.ERROR_FILE_EXISTS : Win32Errors.NERR_UseNotFound); expectedException = "System.NotSupportedException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: Path contains a colon character (:) that is not part of a drive label (C:\\).", expectedException); string invalidPath = SysDrive + @"\dev\test\aaa:aaa.txt"; if (!isLocal) invalidPath = Path.LocalToUnc(invalidPath) + ":aaa.txt"; Directory.CreateDirectory(invalidPath); } catch (NotSupportedException ex) { // win32Error is always 0 for local. if (!isLocal) { 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 // NotSupportedException Console.WriteLine("\nInput Directory Path: [{0}]", tempPath); System.IO.DirectoryInfo dirInfoSysIo = new System.IO.DirectoryInfo(tempPath); DirectoryInfo dirInfo = new DirectoryInfo(tempPath); Assert.AreEqual(dirInfoSysIo.Exists, dirInfo.Exists, "Exists AlphaFS != System.IO"); // Should be false. Assert.IsFalse(dirInfoSysIo.Exists, "System.IO Directory should not exist: [{0}]", tempPath); Assert.IsFalse(dirInfo.Exists, "AlphaFS Directory should not exist: [{0}]", tempPath); StopWatcher(true); dirInfo.Create(true); // Create compressed directory. // dirInfo.Exists should be false. Assert.AreEqual(dirInfoSysIo.Exists, dirInfo.Exists, "AlphaFS Exists should match System.IO"); string root = Path.Combine(tempPath, "Another Sub Directory"); // MAX_PATH hit the road. for (int i = 0; i < level; i++) root = Path.Combine(root, "-" + (i + 1) + "-subdir"); StopWatcher(true); dirInfo = Directory.CreateDirectory(root); report = Reporter(); Console.WriteLine("\n\tCreated directory structure (Should be True): [{0}]{1}", dirInfo.Exists, report); Console.WriteLine("\n\tSubdirectory depth: [{0}], path length: [{1}] characters.", level, root.Length); Assert.IsTrue(Directory.Exists(root), "Directory should exist."); bool compressed = (dirInfo.Attributes & FileAttributes.Compressed) != 0; Console.WriteLine("\n\tCreated compressed directory (Should be True): [{0}]\n", compressed); Assert.IsTrue(compressed, "Directory should be compressed."); } finally { if (Directory.Exists(tempPath, PathFormat.FullPath)) { StopWatcher(true); Directory.Delete(tempPath, true, true); report = Reporter(); exist = Directory.Exists(tempPath); Console.WriteLine("\nDirectory.Delete() (Should be True): [{0}]{1}", !exist, report); Assert.IsFalse(exist, "Cleanup failed: Directory should have been removed."); } } Console.WriteLine(); }
private void DumpGetXxxTime(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network); string path = isLocal ? SysRoot32 : Path.LocalToUnc(SysRoot32); Console.WriteLine("\nInput Directory Path: [{0}]\n", path); #endregion // Setup StopWatcher(true); #region GetCreationTimeXxx DateTime actual = Directory.GetCreationTime(path); DateTime expected = System.IO.Directory.GetCreationTime(path); Console.WriteLine("\tGetCreationTime() : [{0}] System.IO: [{1}]", actual, expected); Assert.AreEqual(expected, actual, "GetCreationTime()"); actual = Directory.GetCreationTimeUtc(path); expected = System.IO.Directory.GetCreationTimeUtc(path); Console.WriteLine("\tGetCreationTimeUtc() : [{0}] System.IO: [{1}]\n", actual, expected); Assert.AreEqual(expected, actual, "GetCreationTimeUtc()"); #endregion // GetCreationTimeXxx #region GetLastAccessTimeXxx actual = Directory.GetLastAccessTime(path); expected = System.IO.Directory.GetLastAccessTime(path); Console.WriteLine("\tGetLastAccessTime() : [{0}] System.IO: [{1}]", actual, expected); Assert.AreEqual(expected, actual, "GetLastAccessTime()"); actual = Directory.GetLastAccessTimeUtc(path); expected = System.IO.Directory.GetLastAccessTimeUtc(path); Console.WriteLine("\tGetLastAccessTimeUtc(): [{0}] System.IO: [{1}]\n", actual, expected); Assert.AreEqual(expected, actual, "GetLastAccessTimeUtc()"); #endregion // GetLastAccessTimeXxx #region GetLastWriteTimeXxx actual = Directory.GetLastWriteTime(path); expected = System.IO.Directory.GetLastWriteTime(path); Console.WriteLine("\tGetLastWriteTime() : [{0}] System.IO: [{1}]", actual, expected); Assert.AreEqual(expected, actual, "GetLastWriteTime()"); actual = Directory.GetLastWriteTimeUtc(path); expected = System.IO.Directory.GetLastWriteTimeUtc(path); Console.WriteLine("\tGetLastWriteTimeUtc() : [{0}] System.IO: [{1}]\n", actual, expected); Assert.AreEqual(expected, actual, "GetLastWriteTimeUtc()"); #endregion // GetLastWriteTimeXxx #region GetChangeTimeXxx Console.WriteLine("\tGetChangeTime() : [{0}] System.IO: [N/A]", Directory.GetChangeTime(path)); Console.WriteLine("\tGetChangeTimeUtc() : [{0}] System.IO: [N/A]", Directory.GetChangeTimeUtc(path)); #endregion GetChangeTimeXxx Console.WriteLine(); Console.WriteLine(Reporter()); Console.WriteLine(); #region Trigger GetChangeTimeXxx // We can not compare ChangeTime against .NET because it does not exist. // Creating a directory and renaming it triggers ChangeTime, so test for that. path = Path.GetTempPath("Directory-GetChangeTimeXxx()-directory-" + Path.GetRandomFileName()); if (!isLocal) path = Path.LocalToUnc(path); DirectoryInfo di = new DirectoryInfo(path); di.Create(); string fileName = di.Name; DateTime lastAccessTimeActual = Directory.GetLastAccessTime(path); DateTime lastAccessTimeUtcActual = Directory.GetLastAccessTimeUtc(path); DateTime changeTimeActual = Directory.GetChangeTime(path); DateTime changeTimeUtcActual = Directory.GetChangeTimeUtc(path); Console.WriteLine("\nTesting ChangeTime on a temp directory."); Console.WriteLine("\nInput Directory Path: [{0}]\n", path); Console.WriteLine("\tGetChangeTime() : [{0}]\t", changeTimeActual); Console.WriteLine("\tGetChangeTimeUtc() : [{0}]\t", changeTimeUtcActual); di.MoveTo(di.FullName.Replace(fileName, fileName + "-Renamed")); // Pause for at least a second so that the difference in time can be seen. int sleep = new Random().Next(2000, 4000); Thread.Sleep(sleep); di.MoveTo(di.FullName.Replace(fileName + "-Renamed", fileName)); DateTime lastAccessTimeExpected = Directory.GetLastAccessTime(path); DateTime lastAccessTimeUtcExpected = Directory.GetLastAccessTimeUtc(path); DateTime changeTimeExpected = Directory.GetChangeTime(path); DateTime changeTimeUtcExpected = Directory.GetChangeTimeUtc(path); Console.WriteLine("\nTrigger ChangeTime by renaming the directory."); Console.WriteLine("For Unit Test, ChangeTime should differ approximately: [{0}] seconds.\n", sleep / 1000); Console.WriteLine("\tGetChangeTime() : [{0}]\t", changeTimeExpected); Console.WriteLine("\tGetChangeTimeUtc() : [{0}]\t\n", changeTimeUtcExpected); Assert.AreNotEqual(changeTimeActual, changeTimeExpected); Assert.AreNotEqual(changeTimeUtcActual, changeTimeUtcExpected); Assert.AreEqual(lastAccessTimeExpected, lastAccessTimeActual); Assert.AreEqual(lastAccessTimeUtcExpected, lastAccessTimeUtcActual); #endregion // Trigger GetChangeTimeXxx di.Delete(); di.Refresh(); // Must Refresh() to get actual state. Assert.IsFalse(di.Exists, "Cleanup failed: Directory should have been removed."); Console.WriteLine(); }