Exemplo n.º 1
0
        private void File_GetSize(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "File-GetSize"))
            {
                var file = rootDir.RandomFileFullPath + ".txt";
                Console.WriteLine("\nInput File Path: [{0}]]", file);

                long streamLength;
                var  ten = UnitTestConstants.TenNumbers.Length;

                using (var fs = System.IO.File.Create(file))
                {
                    // According to NotePad++, creates a file type: "ANSI", which is reported as: "Unicode (UTF-8)".
                    fs.Write(UnitTestConstants.StringToByteArray(UnitTestConstants.TenNumbers), 0, ten);

                    streamLength = fs.Length;
                }


                var fileLength = Alphaleonis.Win32.Filesystem.File.GetSize(file);

                Assert.IsTrue(fileLength == ten && fileLength == streamLength, "File should be [{0}] bytes in size.", ten);
            }

            Console.WriteLine();
        }
        private void AlphaFS_File_CreateSymbolicLink_And_GetLinkTargetInfo(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var fileLink = System.IO.Path.Combine(tempRoot.Directory.FullName, "FileLink-ToOriginalFile.txt");

                var fileInfo = new System.IO.FileInfo(System.IO.Path.Combine(tempRoot.Directory.FullName, "OriginalFile.txt"));
                using (fileInfo.CreateText()) {}

                Console.WriteLine("Input File Path: [{0}]", fileInfo.FullName);
                Console.WriteLine("Input File Link: [{0}]", fileLink);


                Alphaleonis.Win32.Filesystem.File.CreateSymbolicLink(fileLink, fileInfo.FullName);


                var lvi = Alphaleonis.Win32.Filesystem.File.GetLinkTargetInfo(fileLink);
                UnitTestConstants.Dump(lvi);
                Assert.IsTrue(lvi.PrintName.Equals(fileInfo.FullName, StringComparison.OrdinalIgnoreCase));


                UnitTestConstants.Dump(new System.IO.FileInfo(fileLink));

                var alphaFSFileInfo = new Alphaleonis.Win32.Filesystem.FileInfo(fileLink);
                UnitTestConstants.Dump(alphaFSFileInfo.EntryInfo);

                Assert.AreEqual(System.IO.File.Exists(alphaFSFileInfo.FullName), alphaFSFileInfo.Exists);
                Assert.IsFalse(alphaFSFileInfo.EntryInfo.IsDirectory);
                Assert.IsFalse(alphaFSFileInfo.EntryInfo.IsMountPoint);
                Assert.IsTrue(alphaFSFileInfo.EntryInfo.IsReparsePoint);
                Assert.IsTrue(alphaFSFileInfo.EntryInfo.IsSymbolicLink);
                Assert.AreEqual(alphaFSFileInfo.EntryInfo.ReparsePointTag, Alphaleonis.Win32.Filesystem.ReparsePointTag.SymLink);
            }

            Console.WriteLine();
        }
Exemplo n.º 3
0
        private void File_Copy_ExistingFile(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var fileSource = tempRoot.CreateFileRandomizedAttributes();
                var fileCopy   = tempRoot.RandomTxtFileFullPath;

                Console.WriteLine("Src File Path: [{0}] [{1}]", Alphaleonis.Utils.UnitSizeToText(fileSource.Length), fileSource.FullName);
                Console.WriteLine("Dst File Path: [{0}]", fileCopy);


                Alphaleonis.Win32.Filesystem.File.Copy(fileSource.FullName, fileCopy);


                Assert.IsTrue(System.IO.File.Exists(fileCopy), "The file does not exists, but is expected to.");


                Assert.AreEqual(fileSource.Length, new System.IO.FileInfo(fileCopy).Length, "The file sizes do no match, but are expected to.");

                Assert.IsTrue(System.IO.File.Exists(fileSource.FullName), "The original file does not exist, but is expected to.");
            }

            Console.WriteLine();
        }
Exemplo n.º 4
0
        private void File_Replace_NoBackup(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var fileSrc    = tempRoot.RandomTxtFileFullPath;
                var fileDst    = tempRoot.RandomTxtFileFullPath;
                var fileBackup = tempRoot.RandomTxtFileFullPath + "-Backup.txt";
                var text       = System.IO.Path.GetRandomFileName();

                Console.WriteLine("Src    File Path: [{0}]", fileSrc);
                Console.WriteLine("Dst    File Path: [{0}]", fileDst);
                Console.WriteLine("Backup File Path: [{0}]", fileBackup);
                Console.WriteLine("Text            : [{0}]", text);


                using (var stream = System.IO.File.CreateText(fileSrc))
                    stream.Write(text);

                using (var stream = System.IO.File.CreateText(fileDst))
                    stream.Write(text);


                Alphaleonis.Win32.Filesystem.File.Replace(fileSrc, fileDst, null);


                Assert.IsFalse(System.IO.File.Exists(fileSrc), "The file exists, but is expected not to.");

                Assert.IsTrue(System.IO.File.Exists(fileDst), "The file does not exist, but is expected to.");

                Assert.IsFalse(System.IO.File.Exists(fileBackup), "The file exists, but is expected not to.");

                Assert.AreEqual(text, Alphaleonis.Win32.Filesystem.File.ReadAllText(fileDst), "The texts do not match, but are expected to.");
            }

            Console.WriteLine();
        }
Exemplo n.º 5
0
        private void Directory_GetAccessControl(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder = tempRoot.CreateDirectory();

                Console.WriteLine("Input Directory Path: [{0}]", folder.FullName);

                var foundRules = false;

                var sysIO            = System.IO.File.GetAccessControl(folder.FullName);
                var sysIOaccessRules = sysIO.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

                var alphaFS            = System.IO.File.GetAccessControl(folder.FullName);
                var alphaFSaccessRules = alphaFS.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

                Console.WriteLine("\n\tSystem.IO rules found: [{0}]\n\tAlphaFS rules found  : [{1}]", sysIOaccessRules.Count, alphaFSaccessRules.Count);


                Assert.AreEqual(sysIOaccessRules.Count, alphaFSaccessRules.Count);


                foreach (var far in alphaFSaccessRules)
                {
                    UnitTestConstants.Dump(far, -17);

                    UnitTestConstants.TestAccessRules(sysIO, alphaFS);

                    foundRules = true;
                }

                Assert.IsTrue(foundRules);
            }

            Console.WriteLine();
        }
Exemplo n.º 6
0
        private void Directory_Delete_CatchDirectoryNotFoundException_PathIsAFileNotADirectory(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "Directory.Delete"))
            {
                var file = rootDir.RandomFileFullPath + ".txt";
                Console.WriteLine("\nInput File Path: [{0}]\n", file);

                using (System.IO.File.Create(file)) { }


                var gotException = false;
                try
                {
                    Alphaleonis.Win32.Filesystem.Directory.Delete(file);
                }
                catch (Exception ex)
                {
                    var exName = ex.GetType().Name;
                    gotException = exName.Equals("DirectoryNotFoundException", StringComparison.OrdinalIgnoreCase);
                    Console.WriteLine("\n\tCaught Exception: [{0}] Message: [{1}]", exName, ex.Message);
                }
                Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");
            }

            Console.WriteLine();
        }
Exemplo n.º 7
0
        private void Directory_CreateDirectory_CatchAlreadyExistsException_FileExistsWithSameNameAsDirectory(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name))
            {
                var file = rootDir.RandomFileFullPath;
                Console.WriteLine("\nInput File Path: [{0}]", file);

                using (System.IO.File.Create(file)) { }


                var gotException = false;
                try
                {
                    Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(file);
                }
                catch (Exception ex)
                {
                    var exName = ex.GetType().Name;
                    gotException = exName.Equals("AlreadyExistsException", StringComparison.OrdinalIgnoreCase);
                    Console.WriteLine("\n\tCaught {0} Exception: [{1}] {2}", gotException ? "EXPECTED" : "UNEXPECTED", exName, ex.Message);
                }
                Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");
            }

            Console.WriteLine();
        }
        private void AlphaFS_File_GetProcessForFileLock(bool isNetwork)
        {
            var currentProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;


            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var file = tempRoot.CreateFile();

                Console.WriteLine("Input File Path: [{0}]", file.FullName);


                using (file.CreateText())
                {
                    var processes      = Alphaleonis.Win32.Filesystem.File.GetProcessForFileLock(file.FullName);
                    var processesFound = processes.Count;

                    Console.WriteLine("\n\tProcesses found: [{0}]", processesFound);


                    Assert.AreEqual(1, processesFound);


                    foreach (var process in processes)
                    {
                        using (process)
                        {
                            UnitTestConstants.Dump(process, -26);
                            Assert.IsTrue(process.Id == currentProcessId, "File was locked by a process other than the current process.");
                        }
                    }
                }
            }

            Console.WriteLine();
        }
        public void AlphaFS_Path_GetMappedUncName()
        {
            using (var tempRoot = new TemporaryDirectory(true))
            {
                // Randomly test the share where the local folder possibly has the read-only and/or hidden attributes set.

                var folder = tempRoot.CreateDirectoryRandomizedAttributes();


                using (var connection = new Alphaleonis.Win32.Network.DriveConnection(folder.FullName))
                {
                    var driveName = connection.LocalName;

                    Console.WriteLine("Mapped drive letter [{0}] to [{1}]", driveName, folder.FullName);

                    UnitTestConstants.Dump(connection, -9);


                    var connectionName = Alphaleonis.Win32.Filesystem.Path.GetMappedUncName(driveName);

                    Assert.AreEqual(folder.FullName, connectionName);
                }
            }
        }
Exemplo n.º 10
0
        public void AlphaFS_Path_GetFinalPathNameByHandle_ToGetFileStreamName_Success()
        {
            // Issue #438, filestream name.
            // AlphaFS implementation of fileStream.Name returns = "[Unknown]"
            // System.IO returns the full path.


            using (var tempRoot = new TemporaryDirectory())
            {
                var file = tempRoot.CreateFile();

                Console.WriteLine("Input File Path: [{0}]\n", file.FullName);

                string sysIoStreamName;
                using (var fs = file.Create())
                    sysIoStreamName = fs.Name;


                using (var fs = Alphaleonis.Win32.Filesystem.File.Create(file.FullName))
                {
                    var fileStreamName = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(fs.SafeFileHandle);

                    fileStreamName = Alphaleonis.Win32.Filesystem.Path.GetRegularPath(fileStreamName);


                    Console.WriteLine("\tSystem.IO Filestream Name: " + sysIoStreamName);

                    Console.WriteLine("\tAlphaFS   Filestream Name: " + fileStreamName);


                    Assert.AreEqual("[Unknown]", fs.Name);

                    Assert.AreEqual(sysIoStreamName, fileStreamName);
                }
            }
        }
Exemplo n.º 11
0
        private void File_CreateText(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "File.CreateText"))
            {
                var file1 = rootDir.RandomFileFullPath + ".txt";
                var file2 = rootDir.RandomFileFullPath + ".txt";
                Console.WriteLine("\nInput File1 Path: [{0}]", file1);
                Console.WriteLine("\nInput File2 Path: [{0}]", file2);


                using (var stream = System.IO.File.CreateText(file1))
                    stream.Write(UnitTestConstants.TextHelloWorld);


                using (var stream = Alphaleonis.Win32.Filesystem.File.CreateText(file2))
                {
                    stream.Write(UnitTestConstants.TextHelloWorld);
                    Assert.AreEqual(stream.Encoding, Encoding.UTF8, "The text encoding is not equal, but is expected to.");
                }


                Assert.AreEqual(System.IO.File.ReadAllText(file1), System.IO.File.ReadAllText(file2), "The content of the two files is not equal, but is expected to.");
            }

            Console.WriteLine();
        }
        private void AlphaFS_Directory_DeleteEmptySubdirectories_DirectoryContainsAFile_DirectoryRemains(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(tempRoot.Directory.FullName, "Source Folder"));

                Console.WriteLine("Input Directory Path: [{0}]", folder.FullName);


                using (System.IO.File.Create(System.IO.Path.Combine(folder.FullName, "A File"))) { }

                Alphaleonis.Win32.Filesystem.Directory.DeleteEmptySubdirectories(folder.FullName, true);


                folder.Refresh();

                var exists = folder.Exists;
                Console.WriteLine("\n\tFolder exists: [{0}]", exists);

                Assert.IsTrue(folder.Exists);
            }

            Console.WriteLine();
        }
        public void AlphaFS_Directory_CreateJunction_CatchDirectoryNotEmptyException_Local_Success()
        {
            UnitTestConstants.PrintUnitTestHeader(false);

            var tempPath = System.IO.Path.GetTempPath();

            using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name))
            {
                var target   = rootDir.Directory.CreateSubdirectory("JunctionTarget");
                var toDelete = rootDir.Directory.CreateSubdirectory("ToDelete");
                var junction = System.IO.Path.Combine(toDelete.FullName, "JunctionPoint");


                var dirInfo = new System.IO.DirectoryInfo(junction);
                dirInfo.Create();
                // Create an extra folder to trigger the DirectoryNotEmptyException.
                dirInfo.CreateSubdirectory("Extra Folder");


                var gotException = false;

                try
                {
                    Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName);
                }
                catch (Exception ex)
                {
                    var exName = ex.GetType().Name;
                    gotException = exName.Equals("DirectoryNotEmptyException", StringComparison.OrdinalIgnoreCase);
                    Console.WriteLine("\n\tCaught {0} Exception: [{1}] {2}", gotException ? "EXPECTED" : "UNEXPECTED", exName, ex.Message);
                }


                Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");
            }
        }
Exemplo n.º 14
0
        private void File_Delete_CatchUnauthorizedAccessException_PathIsADirectoryNotAFile(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name))
            {
                var folder = rootDir.RandomDirectoryFullPath;
                Console.WriteLine("\nInput Directory Path: [{0}]", folder);

                System.IO.Directory.CreateDirectory(folder);


                var gotException = false;
                try
                {
                    Alphaleonis.Win32.Filesystem.File.Delete(folder);
                }
                catch (Exception ex)
                {
                    var exName = ex.GetType().Name;
                    gotException = exName.Equals("UnauthorizedAccessException", StringComparison.OrdinalIgnoreCase);
                    Console.WriteLine("\n\tCaught {0} Exception: [{1}] {2}", gotException ? "EXPECTED" : "UNEXPECTED", exName, ex.Message);
                }
                Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");
            }

            Console.WriteLine();
        }
Exemplo n.º 15
0
        private void Directory_Copy_CatchDirectoryNotFoundException_NonExistingDirectory(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "Directory.Copy"))
            {
                var folderSrc = System.IO.Path.Combine(rootDir.Directory.FullName, "Source-") + System.IO.Path.GetRandomFileName();
                var folderDst = System.IO.Path.Combine(rootDir.Directory.FullName, "Destination-") + System.IO.Path.GetRandomFileName();
                Console.WriteLine("\nSrc Directory Path: [{0}]", folderSrc);
                Console.WriteLine("Dst Directory Path: [{0}]", folderDst);


                var gotException = false;
                try
                {
                    Alphaleonis.Win32.Filesystem.Directory.Copy(folderSrc, folderDst);
                }
                catch (Exception ex)
                {
                    var exName = ex.GetType().Name;
                    gotException = exName.Equals("DirectoryNotFoundException", StringComparison.OrdinalIgnoreCase);
                    Console.WriteLine("\n\tCaught Exception: [{0}] Message: [{1}]", exName, ex.Message);
                }
                Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");
            }

            Console.WriteLine();
        }
Exemplo n.º 16
0
        private void Directory_SetAccessControl(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "File.SetAccessControl"))
            {
                var folder = rootDir.RandomFileFullPath;
                Directory.CreateDirectory(folder);

                var sysIO            = System.IO.Directory.GetAccessControl(folder);
                var sysIOaccessRules = sysIO.GetAccessRules(true, true, typeof(NTAccount));

                var alphaFS            = Directory.GetAccessControl(folder);
                var alphaFSaccessRules = alphaFS.GetAccessRules(true, true, typeof(NTAccount));


                Console.WriteLine("\nInput Directory Path: [{0}]", folder);
                Console.WriteLine("\n\tSystem.IO rules found: [{0}]\n\tAlphaFS rules found  : [{1}]", sysIOaccessRules.Count, alphaFSaccessRules.Count);
                Assert.AreEqual(sysIOaccessRules.Count, alphaFSaccessRules.Count);


                // Sanity check.
                UnitTestConstants.TestAccessRules(sysIO, alphaFS);


                // Remove inherited properties.
                // Passing true for first parameter protects the new permission from inheritance,
                // and second parameter removes the existing inherited permissions
                Console.WriteLine("\n\tRemove inherited properties and persist it.");
                alphaFS.SetAccessRuleProtection(true, false);
                Directory.SetAccessControl(folder, alphaFS, AccessControlSections.Access);


                // Re-read, using instance methods.
                var sysIOdi   = new System.IO.DirectoryInfo(folder);
                var alphaFSdi = new DirectoryInfo(folder);

                sysIO   = sysIOdi.GetAccessControl(AccessControlSections.Access);
                alphaFS = alphaFSdi.GetAccessControl(AccessControlSections.Access);

                // Sanity check.
                UnitTestConstants.TestAccessRules(sysIO, alphaFS);


                // Restore inherited properties.
                Console.WriteLine("\n\tRestore inherited properties and persist it.");
                alphaFS.SetAccessRuleProtection(false, true);
                Directory.SetAccessControl(folder, alphaFS, AccessControlSections.Access);


                // Re-read.
                sysIO   = System.IO.Directory.GetAccessControl(folder, AccessControlSections.Access);
                alphaFS = Directory.GetAccessControl(folder, AccessControlSections.Access);

                // Sanity check.
                UnitTestConstants.TestAccessRules(sysIO, alphaFS);
            }

            Console.WriteLine();
        }
        private void AlphaFS_Directory_Compress_And_Decompress(bool isNetwork, bool recursive)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder = tempRoot.RandomDirectoryFullPath;

                Console.WriteLine("Input Directory Path: [{0}]", folder);


                var folderAaa = System.IO.Path.Combine(folder, "folder-aaa");
                var folderBbb = System.IO.Path.Combine(folder, "folder-bbb");
                var folderCcc = System.IO.Path.Combine(folderBbb, "folder-ccc");
                System.IO.Directory.CreateDirectory(folderAaa);
                System.IO.Directory.CreateDirectory(folderBbb);
                System.IO.Directory.CreateDirectory(folderCcc);


                var fileAaa = System.IO.Path.Combine(folderAaa, "file-aaa.txt");
                var fileBbb = System.IO.Path.Combine(folderAaa, "file-bbb.txt");
                var fileCcc = System.IO.Path.Combine(folder, "file-ccc.txt");
                var fileDdd = System.IO.Path.Combine(folder, "file-ddd.txt");
                using (System.IO.File.CreateText(fileAaa)) { }
                using (System.IO.File.CreateText(fileBbb)) { }
                using (System.IO.File.CreateText(fileCcc)) { }
                using (System.IO.File.CreateText(fileDdd)) { }


                Alphaleonis.Win32.Filesystem.Directory.Compress(folder, recursive ? Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive : Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.None);


                DirectoryAssert.IsCompressed(folder);
                DirectoryAssert.IsCompressed(folderAaa);
                DirectoryAssert.IsCompressed(folderBbb);
                FileAssert.IsCompressed(fileCcc);
                FileAssert.IsCompressed(fileDdd);


                if (recursive)
                {
                    DirectoryAssert.IsCompressed(folderCcc);
                    FileAssert.IsCompressed(fileAaa);
                    FileAssert.IsCompressed(fileBbb);
                }
                else
                {
                    DirectoryAssert.IsNotCompressed(folderCcc);
                    FileAssert.IsNotCompressed(fileAaa);
                    FileAssert.IsNotCompressed(fileBbb);
                }


                Alphaleonis.Win32.Filesystem.Directory.Decompress(folder, recursive ? Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive : Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.None);


                if (recursive)
                {
                    DirectoryAssert.IsNotCompressed(folderCcc);
                    FileAssert.IsNotCompressed(fileAaa);
                    FileAssert.IsNotCompressed(fileBbb);
                }
                else
                {
                    DirectoryAssert.IsNotCompressed(folderCcc);
                    FileAssert.IsNotCompressed(fileAaa);
                    FileAssert.IsNotCompressed(fileBbb);
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 18
0
        private void DirectoryInfo_MoveTo_DelayUntilReboot(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "DirectoryInfo.MoveTo_DelayUntilReboot"))
            {
                var folder       = rootDir.Directory.FullName;
                var folderSrc    = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(folder, "Source-" + System.IO.Path.GetRandomFileName()));
                var pendingEntry = folderSrc.FullName;

                Console.WriteLine("\nSrc Directory Path: [{0}]", pendingEntry);

                UnitTestConstants.CreateDirectoriesAndFiles(pendingEntry, new Random().Next(5, 15), true);


                // Trigger DelayUntilReboot.
                folderSrc.MoveTo(null, Alphaleonis.Win32.Filesystem.MoveOptions.DelayUntilReboot);


                // Verify DelayUntilReboot in registry.
                var pendingList = (string[])Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager", "PendingFileRenameOperations", null);


                Assert.IsNotNull(pendingList, "The PendingFileRenameOperations is null, which is not expected.");


                var found = false;

                foreach (var line in pendingList)
                {
                    var entry = isNetwork ? pendingEntry.TrimStart('\\') : pendingEntry;

                    var prefix = @"\??\" + (isNetwork ? @"UNC\" : string.Empty);


                    found = !Alphaleonis.Utils.IsNullOrWhiteSpace(line) && line.Replace(entry, string.Empty).Equals(prefix, StringComparison.OrdinalIgnoreCase);
                    if (found)
                    {
                        Console.WriteLine("\n\tPending entry found in registry: [{0}]", line);

                        // TODO: Remove unit test entry from registry.


                        break;
                    }
                }


                Assert.IsTrue(found, "No pending entry found in registry, which is not expected.");
            }

            Console.WriteLine();
        }
        private void AlphaFS_Path_GetRelativePathResolveRelativePath(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var sysDrive = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysDrive) : UnitTestConstants.SysDrive;

                string[] relativePaths =
                {
                    // fso = Folder or file.

                    @"a\b\c",
                    @"a\fso",
                    @"..\..\fso",
                    @"..\b\c",

                    @"a\b\c",
                    @"b\fso",
                    @"b\fso",
                    @"a\b\c",

                    @"a\b\c",
                    @"fso",
                    @"fso",
                    @"a\b\c",

                    @"\a\b\",
                    @"\",
                    @"..\..\",
                    @"a\b\",


                    sysDrive + @"\a",
                    sysDrive + @"\fso",
                    @"..\fso",
                    @"..\a",

                    sysDrive + @"\a",
                    sysDrive + @"\a\fso",
                    @"fso",
                    @"..\a",

                    sysDrive + @"\a",
                    sysDrive + @"\a\b\fso",
                    @"b\fso",
                    @"..\..\a",

                    sysDrive + @"\a",
                    sysDrive + @"\a\b\c\fso",
                    @"b\c\fso",
                    @"..\..\..\a",

                    sysDrive + @"\a",
                    sysDrive + @"\b\fso",
                    @"..\b\fso",
                    @"..\..\a",

                    sysDrive + @"\a",
                    sysDrive + @"\b\c\fso",
                    @"..\b\c\fso",
                    @"..\..\..\a",


                    sysDrive + @"\a\b",
                    sysDrive + @"\a\fso",
                    @"..\fso",
                    @"..\b",

                    sysDrive + @"\a\b",
                    sysDrive + @"\a",
                    @"..\a",
                    @"b",

                    sysDrive + @"\a\b",
                    sysDrive + @"\x\y\fso",
                    @"..\..\x\y\fso",
                    @"..\..\..\a\b",

                    sysDrive + @"\a\b\",
                    sysDrive + @"\",
                    @"..\..\",
                    @"a\b\",


                    sysDrive + @"\a\b\c",
                    sysDrive + @"\a\fso",
                    @"..\..\fso",
                    @"..\b\c",

                    sysDrive + @"\a\b\c",
                    sysDrive + @"\a\x\fso",
                    @"..\..\x\fso",
                    @"..\..\b\c",

                    sysDrive + @"\a\b\c",
                    sysDrive + @"\a\x\y\fso",
                    @"..\..\x\y\fso",
                    @"..\..\..\b\c",

                    sysDrive + @"\a\b\c",
                    sysDrive + @"\fso",
                    @"..\..\..\fso",
                    @"..\a\b\c",


                    tempRoot.Directory.FullName + @"\",
                    tempRoot.Directory.FullName + @"\",
                    string.Empty,
                    string.Empty,


                    tempRoot.Directory.FullName,
                    tempRoot.Directory.FullName,
                    tempRoot.Directory.Name,
                    tempRoot.Directory.Name
                };


                var totalPaths = relativePaths.Length;

                for (var i = 0; i < totalPaths; i += 4)
                {
                    var current          = relativePaths[0 + i];
                    var selected         = relativePaths[1 + i];
                    var shouldBeCurrent  = relativePaths[2 + i];
                    var shouldBeSelected = relativePaths[3 + i];

                    var relative = Alphaleonis.Win32.Filesystem.Path.GetRelativePath(current, selected);
                    var absolute = Alphaleonis.Win32.Filesystem.Path.ResolveRelativePath(current, selected);

                    Console.WriteLine("\tCurrent : [{0}]", current);
                    Console.WriteLine("\tSelected: [{0}]", selected);
                    Console.WriteLine("\tRelative: [{0}]", relative);


                    var verify = System.IO.Path.IsPathRooted(current) && current[0] != Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar;

                    if (verify)
                    {
                        Console.WriteLine("\tAbsolute: [{0}]", absolute);

                        Assert.AreEqual(selected, absolute, "The absolute paths do not match, but are expected to.");
                    }

                    Console.WriteLine();

                    Assert.AreEqual(shouldBeCurrent, relative, "The relative paths do not match, but are expected to.");


                    relative = Alphaleonis.Win32.Filesystem.Path.GetRelativePath(selected, current);
                    absolute = Alphaleonis.Win32.Filesystem.Path.ResolveRelativePath(selected, current);

                    Console.WriteLine("\t  Current : [{0}]", selected);
                    Console.WriteLine("\t  Selected: [{0}]", current);
                    Console.WriteLine("\t  Relative: [{0}]", relative);


                    verify = System.IO.Path.IsPathRooted(selected) && selected[0] != Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar;

                    if (verify)
                    {
                        Console.WriteLine("\t  Absolute: [{0}]", absolute);

                        Assert.AreEqual(current, absolute, "The absolute paths do not match, but are expected to.");
                    }


                    Assert.AreEqual(shouldBeSelected, relative, "The relative paths do not match, but are expected to.");


                    Console.WriteLine();
                }
            }
        }
Exemplo n.º 20
0
        private void AlphaFS_Directory_EnumerateAlternateDataStreams(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder = tempRoot.RandomDirectoryFullPath;

                Console.WriteLine("Input Directory Path: [{0}]", folder);


                var myStream            = "ӍƔŞtrëƛɱ-" + tempRoot.RandomString;
                var myStream2           = "myStreamTWO-" + tempRoot.RandomString;
                var allStreams          = new[] { myStream, myStream2 };
                var streamStringContent = "(1) Computer: [" + Environment.MachineName + "]" + "\tHello there, " + Environment.UserName;

                Console.WriteLine("\nA directory is created and {0} streams are added.", allStreams.Length.ToString(CultureInfo.CurrentCulture));

                var di = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder);
                di.Create();


                const int defaultStreamsDirectory = 0; // The default number of data streams for a folder.
                var       currentNumberofStreams  = di.EnumerateAlternateDataStreams().Count();

                Assert.AreEqual(defaultStreamsDirectory, currentNumberofStreams, "Total amount of default streams do not match.");
                Assert.AreEqual(currentNumberofStreams, Alphaleonis.Win32.Filesystem.Directory.EnumerateAlternateDataStreams(folder).Count(), "Total amount of Directory.EnumerateAlternateDataStreams() 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.

                var stream1Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream;
                var stream2Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream2;

                Alphaleonis.Win32.Filesystem.File.WriteAllLines(stream1Name, UnitTestConstants.StreamArrayContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);
                Alphaleonis.Win32.Filesystem.File.WriteAllText(stream2Name, streamStringContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);



                var newNumberofStreams = Alphaleonis.Win32.Filesystem.Directory.EnumerateAlternateDataStreams(folder).Count();
                Console.WriteLine("\n\nNew 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 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 Alphaleonis.Win32.Filesystem.File.ReadAllLines(folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + streamName, Alphaleonis.Win32.Filesystem.PathFormat.FullPath))
                    {
                        Console.WriteLine("\t\t{0}", line);
                    }
                }



                // Show DirectoryInfo instance data of the streams.

                var dirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(stream1Name, Alphaleonis.Win32.Filesystem.PathFormat.LongFullPath);

                Console.WriteLine();
                UnitTestConstants.Dump(dirInfo, -17);



                // Show FileInfo instance data of the streams.

                var fileInfo1 = new Alphaleonis.Win32.Filesystem.FileInfo(stream1Name, Alphaleonis.Win32.Filesystem.PathFormat.LongFullPath);
                var fileInfo2 = new Alphaleonis.Win32.Filesystem.FileInfo(stream2Name, Alphaleonis.Win32.Filesystem.PathFormat.LongFullPath);

                Console.WriteLine();
                UnitTestConstants.Dump(fileInfo1, -17);
                UnitTestConstants.Dump(fileInfo2, -17);


                Assert.AreEqual(myStream, fileInfo1.Name);
                Assert.AreEqual(myStream2, fileInfo2.Name);

                Assert.IsNull(fileInfo1.EntryInfo);
                Assert.IsNull(fileInfo2.EntryInfo);
            }

            Console.WriteLine();
        }
        private void AlphaFS_EnumerateAlternateDataStreams(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var file = tempRoot.RandomTxtFileFullPath;

                Console.WriteLine("Input File Path: [{0}]", file);


                var myStream            = "ӍƔŞtrëƛɱ-" + tempRoot.RandomString;
                var myStream2           = "myStreamTWO-" + tempRoot.RandomString;
                var allStreams          = new[] { myStream, myStream2 };
                var streamStringContent = "(1) Computer: [" + Environment.MachineName + "]" + "\tHello there, " + Environment.UserName;
                var tenNumbers          = "0123456789";

                Console.WriteLine("\nA file is created and {0} streams are added.", allStreams.Length.ToString(CultureInfo.CurrentCulture));

                // Create file and add 10 characters to it, file is created in ANSI format.
                System.IO.File.WriteAllText(file, tenNumbers);


                var fi = new Alphaleonis.Win32.Filesystem.FileInfo(file);

                const int defaultStreamsFile     = 1; // The default number of data streams for a file.
                var       currentNumberofStreams = fi.EnumerateAlternateDataStreams().Count();


                Assert.AreEqual(defaultStreamsFile, currentNumberofStreams, "Total amount of default streams do not match.");
                Assert.AreEqual(currentNumberofStreams, Alphaleonis.Win32.Filesystem.File.EnumerateAlternateDataStreams(file).Count(), "Total amount of File.EnumerateAlternateDataStreams() streams do not match.");


                var fileSize = Alphaleonis.Win32.Filesystem.File.GetSize(file);
                Assert.AreEqual(tenNumbers.Length, fileSize);


                // 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.

                var stream1Name = file + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream;
                var stream2Name = file + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream2;

                Alphaleonis.Win32.Filesystem.File.WriteAllLines(stream1Name, UnitTestConstants.StreamArrayContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);
                Alphaleonis.Win32.Filesystem.File.WriteAllText(stream2Name, streamStringContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);



                var newNumberofStreams = Alphaleonis.Win32.Filesystem.File.EnumerateAlternateDataStreams(file).Count();
                Console.WriteLine("\n\nNew stream count: [{0}]", newNumberofStreams);


                // Enumerate all streams from the file.
                foreach (var stream in fi.EnumerateAlternateDataStreams())
                {
                    Assert.IsTrue(UnitTestConstants.Dump(stream, -10));

                    // The default stream, a file as we know it.
                    if (Alphaleonis.Utils.IsNullOrWhiteSpace(stream.StreamName))
                    {
                        Assert.AreEqual(fileSize, stream.Size);
                    }
                }


                // Show the contents of our streams.
                Console.WriteLine();
                foreach (var streamName in 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 Alphaleonis.Win32.Filesystem.File.ReadAllLines(file + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + streamName, Alphaleonis.Win32.Filesystem.PathFormat.FullPath))
                    {
                        Console.WriteLine("\t\t{0}", line);
                    }
                }



                // Show FileInfo instance data of the streams.

                var fileInfo1 = new Alphaleonis.Win32.Filesystem.FileInfo(stream1Name, Alphaleonis.Win32.Filesystem.PathFormat.LongFullPath);
                var fileInfo2 = new Alphaleonis.Win32.Filesystem.FileInfo(stream2Name, Alphaleonis.Win32.Filesystem.PathFormat.LongFullPath);

                Console.WriteLine();
                UnitTestConstants.Dump(fileInfo1, -17);
                UnitTestConstants.Dump(fileInfo2, -17);


                Assert.AreEqual(myStream, fileInfo1.Name);
                Assert.AreEqual(myStream2, fileInfo2.Name);

                Assert.IsNull(fileInfo1.EntryInfo);
                Assert.IsNull(fileInfo2.EntryInfo);
            }

            Console.WriteLine();
        }
Exemplo n.º 22
0
        private void DirectoryInfo_Refresh(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "DirectoryInfo.Refresh"))
            {
                var folder    = rootDir.RandomFileFullPath;
                var diSysIo   = new System.IO.DirectoryInfo(folder + "-System.IO");
                var diAlphaFS = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder + "-AlphaFS");

                Console.WriteLine("\nSystem.IO Input Directory Path: [{0}]", diSysIo.FullName);
                Console.WriteLine("AlphaFS   Input Directory Path: [{0}]", diAlphaFS.FullName);


                var existsSysIo = diSysIo.Exists;
                var exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsFalse(exists, "The directory exists, but is expected not to.");


                diSysIo.Create();
                diAlphaFS.Create();
                existsSysIo = diSysIo.Exists;
                exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsFalse(exists, "The directory exists, but is expected not to.");


                diSysIo.Refresh();
                diAlphaFS.Refresh();
                existsSysIo = diSysIo.Exists;
                exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsTrue(exists, "The directory does not exists, but is expected to.");


                diSysIo.Delete();
                diAlphaFS.Delete();
                existsSysIo = diSysIo.Exists;
                exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsTrue(exists, "The directory does not exists, but is expected to.");


                diSysIo.Refresh();
                diAlphaFS.Refresh();
                existsSysIo = diSysIo.Exists;
                exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsFalse(exists, "The directory exists, but is expected not to.");
            }

            Console.WriteLine();
        }
        public void Directory_Move_FileToMappedDriveLetter_LocalAndNetwork_Success()
        {
            // Do not pass isNetwork, as to always use UnitTestConstants.TempPath

            using (var tempRoot = new TemporaryDirectory())
            {
                const string srcFileName = "Src file.log";
                const string dstFileName = "Dst file.log";

                var srcFile = System.IO.Path.Combine(tempRoot.Directory.FullName, srcFileName);


                var drive   = Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter() + @":\";
                var share   = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempRoot.Directory.Parent.FullName);
                var dstFile = System.IO.Path.Combine(drive, dstFileName);

                Alphaleonis.Win32.Network.Host.ConnectDrive(drive, share);

                Console.WriteLine("Mapped drive [{0}] to [{1}]\n", drive, share);


                System.IO.File.AppendAllText(srcFile, new string('*', new Random().Next(1, 1024)));

                const Alphaleonis.Win32.Filesystem.MoveOptions options = Alphaleonis.Win32.Filesystem.MoveOptions.CopyAllowed | Alphaleonis.Win32.Filesystem.MoveOptions.WriteThrough | Alphaleonis.Win32.Filesystem.MoveOptions.ReplaceExisting;

                Console.WriteLine("Src File Path: [{0}]", srcFile);
                Console.WriteLine("Dst File Path: [{0}]", dstFile);



                var cmr = Alphaleonis.Win32.Filesystem.Directory.Move(srcFile, dstFile, options);

                UnitTestConstants.Dump(cmr);


                Assert.IsFalse(System.IO.Directory.Exists(dstFile));

                Assert.IsTrue(System.IO.File.Exists(dstFile));

                Assert.AreEqual(new System.IO.FileInfo(srcFile).Length, new System.IO.FileInfo(dstFile).Length);


                Assert.IsTrue(cmr.IsCopy);
                Assert.IsTrue(cmr.IsEmulatedMove);

                Assert.IsTrue(cmr.IsFile);
                Assert.IsFalse(cmr.IsDirectory);

                Assert.IsFalse(cmr.IsCanceled);
                Assert.AreEqual(0, cmr.TotalFolders);
                Assert.AreEqual(1, cmr.TotalFiles);


                System.IO.File.Delete(dstFile);


                Alphaleonis.Win32.Network.Host.DisconnectDrive(drive);
            }


            Console.WriteLine();
        }
Exemplo n.º 24
0
        private void DirectoryInfo_MoveTo_DelayUntilReboot(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);
            Console.WriteLine();


            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name))
            {
                var folder       = rootDir.Directory.FullName;
                var folderSrc    = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(folder, "Source-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()));
                var pendingEntry = folderSrc.FullName;

                Console.WriteLine("Src Directory Path: [{0}]", pendingEntry);

                UnitTestConstants.CreateDirectoriesAndFiles(pendingEntry, 1, false, false, true);


                var gotException = false;


                try
                {
                    // Trigger DelayUntilReboot.

                    folderSrc.MoveTo(null, Alphaleonis.Win32.Filesystem.MoveOptions.DelayUntilReboot);
                }
                catch (Exception ex)
                {
                    var exType = ex.GetType();

                    gotException = exType == typeof(ArgumentException);

                    Console.WriteLine("\n\tCaught {0} Exception: [{1}] {2}", gotException ? "EXPECTED" : "UNEXPECTED", exType.Name, ex.Message);
                }



                if (isNetwork)
                {
                    Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");
                }

                else
                {
                    // Verify DelayUntilReboot in registry.

                    var pendingList = (string[])Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager", "PendingFileRenameOperations", null);


                    Assert.IsNotNull(pendingList, "The PendingFileRenameOperations is null, but is not expected to.");


                    var found = false;

                    foreach (var line in pendingList)
                    {
                        found = !Alphaleonis.Utils.IsNullOrWhiteSpace(line) && line.Replace(pendingEntry, string.Empty).Equals(Alphaleonis.Win32.Filesystem.Path.NonInterpretedPathPrefix, StringComparison.Ordinal);

                        if (found)
                        {
                            Console.WriteLine("\n\tPending entry found in registry: [{0}]", line);

                            // TODO: Remove unit test entry from registry.

                            break;
                        }
                    }


                    Assert.IsTrue(found, "Registry does not contain pending entry, but is expected to.");
                }
            }

            Console.WriteLine();
        }
        private void Directory_Move_ToDifferentVolume_EmulateUsingCopyDelete(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);
            Console.WriteLine();


            using (var rootDir = new TemporaryDirectory(UnitTestConstants.TempFolder, MethodBase.GetCurrentMethod().Name))
            {
                var random         = UnitTestConstants.GetRandomFileNameWithDiacriticCharacters();
                var srcFolderName  = System.IO.Path.Combine(rootDir.Directory.FullName, "Existing Source Folder.") + random;
                var destFolderName = System.IO.Path.Combine(rootDir.Directory.FullName, "Destination Folder.") + random;


                var folderSrc = isNetwork
               ? System.IO.Directory.CreateDirectory(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(srcFolderName))
               : System.IO.Directory.CreateDirectory(System.IO.Path.Combine(srcFolderName));

                var folderDst = !isNetwork
               ? new System.IO.DirectoryInfo(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(destFolderName))
               : new System.IO.DirectoryInfo(destFolderName);


                Console.WriteLine("\nSrc Directory Path: [{0}]", folderSrc.FullName);
                Console.WriteLine("Dst Directory Path: [{0}]", folderDst.FullName);

                UnitTestConstants.CreateDirectoriesAndFiles(folderSrc.FullName, new Random().Next(5, 15), false, false, true);


                var dirEnumOptions = Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.FilesAndFolders | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive;

                var props            = Alphaleonis.Win32.Filesystem.Directory.GetProperties(folderSrc.FullName, dirEnumOptions);
                var sourceTotal      = props["Total"];
                var sourceTotalFiles = props["File"];
                var sourceTotalSize  = props["Size"];

                Console.WriteLine("\n\tTotal size: [{0}] - Total Folders: [{1}] - Files: [{2}]", Alphaleonis.Utils.UnitSizeToText(sourceTotalSize), sourceTotal - sourceTotalFiles, sourceTotalFiles);



                var moveResult = Alphaleonis.Win32.Filesystem.Directory.Move(folderSrc.FullName, folderDst.FullName, Alphaleonis.Win32.Filesystem.MoveOptions.CopyAllowed);

                UnitTestConstants.Dump(moveResult, -16);

                props = Alphaleonis.Win32.Filesystem.Directory.GetProperties(folderDst.FullName, dirEnumOptions);
                Assert.AreEqual(sourceTotal, props["Total"], "The number of total file system objects do not match.");
                Assert.AreEqual(sourceTotalFiles, props["File"], "The number of total files do not match.");
                Assert.AreEqual(sourceTotalSize, props["Size"], "The total file size does not match.");


                // Test against moveResult results.

                var isMove = moveResult.IsMove;

                Assert.AreEqual(sourceTotal, moveResult.TotalFolders + moveResult.TotalFiles, "The number of total file system objects do not match.");
                Assert.AreEqual(sourceTotalFiles, moveResult.TotalFiles, "The number of total files do not match.");
                Assert.AreEqual(sourceTotalSize, moveResult.TotalBytes, "The total file size does not match.");
                Assert.IsFalse(isMove, "The action was expected to be a Copy, not a Move.");
                Assert.IsTrue(moveResult.IsEmulatedMove, "The action was expected to be emulated (Copy + Delete).");

                Assert.IsFalse(System.IO.Directory.Exists(folderSrc.FullName), "The original folder exists, but is expected not to.");
            }


            Console.WriteLine();
        }
        private void Directory_Compress_Decompress(bool isNetwork, bool recursive)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "Directory.Decompress"))
            {
                var rootFolder = rootDir.RandomFileFullPath + ".txt";
                Console.WriteLine("\nInput Directory Path: [{0}]", rootFolder);


                var folderAaa = System.IO.Path.Combine(rootFolder, "folder-aaa");
                var folderBbb = System.IO.Path.Combine(rootFolder, "folder-bbb");
                var folderCcc = System.IO.Path.Combine(folderBbb, "folder-ccc");
                System.IO.Directory.CreateDirectory(folderAaa);
                System.IO.Directory.CreateDirectory(folderBbb);
                System.IO.Directory.CreateDirectory(folderCcc);


                var fileAaa = System.IO.Path.Combine(folderAaa, "file-aaa.txt");
                var fileBbb = System.IO.Path.Combine(folderAaa, "file-bbb.txt");
                var fileCcc = System.IO.Path.Combine(rootFolder, "file-ccc.txt");
                var fileDdd = System.IO.Path.Combine(rootFolder, "file-ddd.txt");
                using (System.IO.File.CreateText(fileAaa)) { }
                using (System.IO.File.CreateText(fileBbb)) { }
                using (System.IO.File.CreateText(fileCcc)) { }
                using (System.IO.File.CreateText(fileDdd)) { }


                Alphaleonis.Win32.Filesystem.Directory.Compress(rootFolder, recursive ? Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive : Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.None);


                DirectoryAssert.IsCompressed(rootFolder);
                DirectoryAssert.IsCompressed(folderAaa);
                DirectoryAssert.IsCompressed(folderBbb);
                FileAssert.IsCompressed(fileCcc);
                FileAssert.IsCompressed(fileDdd);


                if (recursive)
                {
                    DirectoryAssert.IsCompressed(folderCcc);
                    FileAssert.IsCompressed(fileAaa);
                    FileAssert.IsCompressed(fileBbb);
                }
                else
                {
                    DirectoryAssert.IsNotCompressed(folderCcc);
                    FileAssert.IsNotCompressed(fileAaa);
                    FileAssert.IsNotCompressed(fileBbb);
                }


                Alphaleonis.Win32.Filesystem.Directory.Decompress(rootFolder, recursive ? Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive : Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.None);


                if (recursive)
                {
                    DirectoryAssert.IsNotCompressed(folderCcc);
                    FileAssert.IsNotCompressed(fileAaa);
                    FileAssert.IsNotCompressed(fileBbb);
                }
                else
                {
                    DirectoryAssert.IsNotCompressed(folderCcc);
                    FileAssert.IsNotCompressed(fileAaa);
                    FileAssert.IsNotCompressed(fileBbb);
                }
            }

            Console.WriteLine();
        }
        private void Directory_GetXxxTimeXxx(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name))
            {
                var folder = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysRoot32) : UnitTestConstants.SysRoot32;

                Console.WriteLine("\nInput Directory Path: [{0}]", folder);


                Assert.AreEqual(System.IO.Directory.GetCreationTime(folder), Alphaleonis.Win32.Filesystem.Directory.GetCreationTime(folder));
                Assert.AreEqual(System.IO.Directory.GetCreationTimeUtc(folder), Alphaleonis.Win32.Filesystem.Directory.GetCreationTimeUtc(folder));
                Assert.AreEqual(System.IO.Directory.GetLastAccessTime(folder), Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTime(folder));
                Assert.AreEqual(System.IO.Directory.GetLastAccessTimeUtc(folder), Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTimeUtc(folder));
                Assert.AreEqual(System.IO.Directory.GetLastWriteTime(folder), Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTime(folder));
                Assert.AreEqual(System.IO.Directory.GetLastWriteTimeUtc(folder), Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTimeUtc(folder));


                // We cannot compare ChangeTime against .NET because it does not exist.
                // Creating a directory and renaming it triggers ChangeTime, so test for that.

                folder = rootDir.RandomDirectoryFullPath;
                if (isNetwork)
                {
                    folder = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(folder);
                }
                Console.WriteLine("Input Directory Path: [{0}]", folder);

                var dirInfo = new System.IO.DirectoryInfo(folder);
                dirInfo.Create();
                var fileName = dirInfo.Name;


                var changeTimeActual    = Alphaleonis.Win32.Filesystem.Directory.GetChangeTime(folder);
                var changeTimeUtcActual = Alphaleonis.Win32.Filesystem.Directory.GetChangeTimeUtc(folder);


                // Sleep for three seconds.
                var delay = 3;

                dirInfo.MoveTo(dirInfo.FullName.Replace(fileName, fileName + "-Renamed"));
                Thread.Sleep(delay * 1000);
                dirInfo.MoveTo(dirInfo.FullName.Replace(fileName + "-Renamed", fileName));


                var newChangeTime = changeTimeActual.AddSeconds(delay);
                Assert.AreEqual(changeTimeActual.AddSeconds(delay), newChangeTime);

                newChangeTime = changeTimeUtcActual.AddSeconds(delay);
                Assert.AreEqual(changeTimeUtcActual.AddSeconds(delay), newChangeTime);
            }
        }
        private void AlphaFS_File_Copy_3ExistingFiles_FromVolumeShadowCopy(bool isNetwork)
        {
            var testOk = false;

            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder = tempRoot.CreateDirectoryRandomizedAttributes();

                var dosDevices = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("HarddiskVolumeShadowCopy", StringComparison.OrdinalIgnoreCase)).ToArray();

                foreach (var dosDevice in dosDevices)
                {
                    if (testOk)
                    {
                        break;
                    }

                    var shadowSource = Alphaleonis.Win32.Filesystem.Path.GlobalRootDevicePrefix + dosDevice;

                    var sourceFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

                    var drive = System.IO.Directory.GetDirectoryRoot(sourceFolder).TrimEnd('\\');

                    var globalRoot = sourceFolder.Replace(drive, shadowSource);


                    var dirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(globalRoot);

                    Console.WriteLine("Input GlobalRoot Path: [{0}]\n", dirInfo.FullName);

                    if (!dirInfo.Exists)
                    {
                        UnitTestAssert.InconclusiveBecauseFileNotFound("No volume shadow copy found.");
                    }


                    var enumOptions = Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.SkipReparsePoints;

                    var copyCount = 0;

                    foreach (var fileSource in dirInfo.EnumerateFiles(enumOptions))
                    {
                        if (copyCount == 3)
                        {
                            break;
                        }


                        var fileCopy = System.IO.Path.Combine(folder.FullName, System.IO.Path.GetFileName(fileSource.FullName));

                        Console.WriteLine("Copy file #{0}.", copyCount + 1);


                        var cmr = Alphaleonis.Win32.Filesystem.File.Copy(fileSource.FullName, fileCopy, Alphaleonis.Win32.Filesystem.CopyOptions.None);


                        UnitTestConstants.Dump(cmr);
                        Console.WriteLine();


                        Assert.AreEqual((int)Alphaleonis.Win32.Win32Errors.NO_ERROR, cmr.ErrorCode);


                        testOk = true;

                        copyCount++;
                    }
                }
            }


            Console.WriteLine();


            if (!testOk)
            {
                UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable();
            }
        }
Exemplo n.º 29
0
        private void BackupFileStream_InitializeInstance(bool isNetwork)
        {
            if (!System.IO.File.Exists(UnitTestConstants.NotepadExe))
            {
                Assert.Inconclusive("Test ignored because {0} was not found.", UnitTestConstants.NotepadExe);
            }


            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, "BackupFileStream"))
            {
                var file = System.IO.Path.Combine(rootDir.Directory.FullName, System.IO.Path.GetFileName(UnitTestConstants.NotepadExe));
                Console.WriteLine("\nInput File Path: [{0}]\n", file);


                System.IO.File.Copy(UnitTestConstants.NotepadExe, file);


                using (var bfs = new Alphaleonis.Win32.Filesystem.BackupFileStream(file, System.IO.FileMode.Open))
                {
                    #region IOException

                    bfs.Lock(0, 10);

                    var gotException = false;
                    try
                    {
                        bfs.Lock(0, 10);
                    }
                    catch (Exception ex)
                    {
                        var exName = ex.GetType().Name;
                        gotException = exName.Equals("IOException", StringComparison.OrdinalIgnoreCase);
                        Console.WriteLine("\tCaught Exception (Expected): [{0}] Message: [{1}]", exName, ex.Message);
                    }
                    Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");

                    bfs.Unlock(0, 10);

                    #endregion // IOException

                    #region IOException #2

                    gotException = false;
                    try
                    {
                        bfs.Unlock(0, 10);
                    }
                    catch (Exception ex)
                    {
                        var exName = ex.GetType().Name;
                        gotException = exName.Equals("IOException", StringComparison.OrdinalIgnoreCase);
                        Console.WriteLine("\tCaught Exception (Expected): [{0}] Message: [{1}]", exName, ex.Message);
                    }
                    Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");

                    #endregion // IOException #2


                    UnitTestConstants.Dump(bfs.ReadStreamInfo(), -10);
                    Console.WriteLine();

                    UnitTestConstants.Dump(bfs, -14);
                    Console.WriteLine();
                }
            }

            Console.WriteLine();
        }
        private void Directory_SetTimestampsXxx(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }

            var rnd = new Random();


            using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name))
            {
                var folder      = rootDir.RandomDirectoryFullPath;
                var symlinkPath = System.IO.Path.Combine(rootDir.Directory.FullName, UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()) + "-symlink";

                Console.WriteLine("\nInput Directory Path: [{0}]", folder);


                System.IO.Directory.CreateDirectory(folder);
                Alphaleonis.Win32.Filesystem.Directory.CreateSymbolicLink(symlinkPath, folder);


                var creationTime   = new DateTime(rnd.Next(1971, 2071), rnd.Next(1, 12), rnd.Next(1, 28), rnd.Next(0, 23), rnd.Next(0, 59), rnd.Next(0, 59));
                var lastAccessTime = new DateTime(rnd.Next(1971, 2071), rnd.Next(1, 12), rnd.Next(1, 28), rnd.Next(0, 23), rnd.Next(0, 59), rnd.Next(0, 59));
                var lastWriteTime  = new DateTime(rnd.Next(1971, 2071), rnd.Next(1, 12), rnd.Next(1, 28), rnd.Next(0, 23), rnd.Next(0, 59), rnd.Next(0, 59));


                Alphaleonis.Win32.Filesystem.Directory.SetTimestamps(folder, creationTime, lastAccessTime, lastWriteTime);


                Assert.AreEqual(System.IO.Directory.GetCreationTime(folder), creationTime);
                Assert.AreEqual(System.IO.Directory.GetLastAccessTime(folder), lastAccessTime);
                Assert.AreEqual(System.IO.Directory.GetLastWriteTime(folder), lastWriteTime);


                // SymbolicLink
                Alphaleonis.Win32.Filesystem.Directory.SetTimestamps(symlinkPath, creationTime.AddDays(1), lastAccessTime.AddDays(1), lastWriteTime.AddDays(1), true, Alphaleonis.Win32.Filesystem.PathFormat.RelativePath);
                Assert.AreEqual(System.IO.Directory.GetCreationTime(symlinkPath), Alphaleonis.Win32.Filesystem.Directory.GetCreationTime(symlinkPath));
                Assert.AreEqual(System.IO.Directory.GetLastAccessTime(symlinkPath), Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTime(symlinkPath));
                Assert.AreEqual(System.IO.Directory.GetLastWriteTime(symlinkPath), Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTime(symlinkPath));


                creationTime   = new DateTime(rnd.Next(1971, 2071), rnd.Next(1, 12), rnd.Next(1, 28), rnd.Next(0, 23), rnd.Next(0, 59), rnd.Next(0, 59));
                lastAccessTime = new DateTime(rnd.Next(1971, 2071), rnd.Next(1, 12), rnd.Next(1, 28), rnd.Next(0, 23), rnd.Next(0, 59), rnd.Next(0, 59));
                lastWriteTime  = new DateTime(rnd.Next(1971, 2071), rnd.Next(1, 12), rnd.Next(1, 28), rnd.Next(0, 23), rnd.Next(0, 59), rnd.Next(0, 59));


                Alphaleonis.Win32.Filesystem.Directory.SetTimestampsUtc(folder, creationTime, lastAccessTime, lastWriteTime);


                Assert.AreEqual(System.IO.Directory.GetCreationTimeUtc(folder), creationTime);
                Assert.AreEqual(System.IO.Directory.GetLastAccessTimeUtc(folder), lastAccessTime);
                Assert.AreEqual(System.IO.Directory.GetLastWriteTimeUtc(folder), lastWriteTime);


                // SymbolicLink
                Alphaleonis.Win32.Filesystem.Directory.SetTimestampsUtc(symlinkPath, creationTime.AddDays(1), lastAccessTime.AddDays(1), lastWriteTime.AddDays(1), true, Alphaleonis.Win32.Filesystem.PathFormat.RelativePath);
                Assert.AreEqual(System.IO.Directory.GetCreationTimeUtc(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetCreationTimeUtc(symlinkPath));
                Assert.AreEqual(System.IO.Directory.GetLastAccessTimeUtc(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetLastAccessTimeUtc(symlinkPath));
                Assert.AreEqual(System.IO.Directory.GetLastWriteTimeUtc(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetLastWriteTimeUtc(symlinkPath));
            }

            Console.WriteLine();
        }