public static string FindVcsRootPath()
        {
            Assembly ncrunchAssembly = null;
            try
            {
                ncrunchAssembly =
                    AppDomain.CurrentDomain.Load("NCrunch.Framework");

                Type ncrunchType =
                    ncrunchAssembly.GetTypes()
                        .FirstOrDefault(
                            type => type.Name.Equals("NCrunchEnvironment", StringComparison.InvariantCultureIgnoreCase));

                if (ncrunchType != null)
                {
                    MethodInfo method = ncrunchType.GetMethod("GetOriginalSolutionPath");

                    if (method != null)
                    {
                        string originalSolutionPath = method.Invoke(null, null) as string;
                        if (!string.IsNullOrWhiteSpace(originalSolutionPath))
                        {
                            DirectoryInfo parent = new DirectoryInfo(originalSolutionPath).Parent;
                            return VcsPathHelper.FindVcsRootPath(parent.FullName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return VcsPathHelper.FindVcsRootPath();
        }
Пример #2
0
        private static void SetSecurityAlpha(string directory)
        {
            //create the test structure
            if (Directory.Exists(directory))
            {
                Directory.Delete(directory, true);
            }

            Directory.CreateDirectory(directory);
            Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited"));
            DirectoryInfo testDirInfo = new DirectoryInfo(directory);
            //System.IO.Directory.CreateDirectory(_testDir);
            //System.IO.Directory.CreateDirectory(System.IO.Path.Combine(_testDir, "inherited"));
            //System.IO.DirectoryInfo testDirInfo = new System.IO.DirectoryInfo(_testDir);

            var ds = testDirInfo.GetAccessControl(AccessControlSections.Access);

            ds.SetAccessRuleProtection(true, false);
            ds.AddAccessRule(new FileSystemAccessRule(
                                 identity: new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                 fileSystemRights: FileSystemRights.FullControl,
                                 inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                 propagationFlags: PropagationFlags.None,
                                 type: AccessControlType.Allow
                                 ));

            //using (new PrivilegeEnabler(Privilege.Impersonate, Privilege.Backup, Privilege.Restore, Privilege.Security, Privilege.TakeOwnership, Privilege.TrustedCredManAccess, Privilege.Audit))
            {
                testDirInfo.SetAccessControl(ds);
            }
        }
Пример #3
0
 public static string GetVolumePath(string path, out bool IsMountPoint)
 {
     if (string.IsNullOrEmpty(path))
         throw new ArgumentNullException("path");
     if (Path.GetPathRoot(path).Equals(path, StringComparison.OrdinalIgnoreCase))
     {
         IsMountPoint = false;
         return path;
     }
     if (Directory.Exists(path))
     {
         FileSystemEntryInfo seInfo = File.GetFileSystemEntryInfo(path);
         if (seInfo.IsReparsePoint && seInfo.IsMountPoint)
         {
             IsMountPoint = true;
             return path;
         }
         else
         {
             var dInfo = new DirectoryInfo(path);
             return GetVolumePath(dInfo.Parent.FullName, out IsMountPoint);
         }
     }
     else
     {
         throw new Exception(String.Format("{0} does not exist.", path));
     }
 }
Пример #4
0
        private static IEnumerable <string> EnumerateFilesWithFilters(string path, IList <string> patterns,
                                                                      Gitignore gitignore, FileFilter filter)
        {
            DirectoryInfo di = new DirectoryInfo(path);

            // the root of the drive has the hidden attribute set, so don't stop on this hidden directory
            if (di.Attributes.HasFlag(FileAttributes.Hidden) && (di.Root != di))
            {
                yield break;
            }

            int startDepth = 0;

            if (filter.MaxSubfolderDepth > 0)
            {
                startDepth = GetDepth(di);
            }

            IEnumerable <string> directories = new string[] { path };

            if (filter.IncludeSubfolders)
            {
                directories = directories.Concat(EnumerateDirectoriesImpl(path, filter, startDepth, gitignore));
            }

            foreach (var directory in directories)
            {
                IEnumerable <string> matches = EnumerateFilesImpl(directory, patterns, filter, gitignore);

                foreach (var file in matches)
                {
                    yield return(file);
                }
            }
        }
Пример #5
0
        static void Main(string[] args)
        {
            ConfigureSpeech();
            Console.BufferWidth = 150;
            Console.WindowWidth = 150;
            _sourceFolder       = new DirectoryInfo(args[0]);
            _initialDrives      = DriveInfo.GetDrives();
            Console.WriteLine($"Initial Drives: {_initialDrives.Select(d => d.Name).ToDelimitedString(", ")}");
            Task.Run(() => MonitorDrives());
            Console.WriteLine($"Started Monitorind Drives...");
            Task.Run(() => MonitorReadyToCopyQueue());
            Console.WriteLine($"Ready to copy data from {_sourceFolder} to your USB sticks, put them in these thiny wholes :P");

            while (true)
            {
                if (_askForPositionQueue.TryDequeue(out var driveToProcess))
                {
                    Console.Write($"New USB Stick detected (Label: '{driveToProcess.VolumeLabel}', Name: '{driveToProcess.Name}') please enter location: ");
                    var location = Console.ReadLine();
                    Console.WriteLine($"Start copy from '{_sourceFolder.FullName}' to '{driveToProcess.Name}', location: {location}");
                    _readyToCopyQueue.Enqueue(Tuple.Create(driveToProcess, location));
                }

                if (_finishedQueue.TryDequeue(out var info))
                {
                    var x = info ?? null;
                    Console.WriteLine($"Copy finished on '{ x.Item1.VolumeLabel}', Name: '{x.Item1.Name}') at location: '{x.Item2}'");
                    Console.Write("Please remove Drive and press any key to confirm.");
                    _synth.Speak("Please confirm you fagot.");
                    Console.ReadKey(intercept: true);
                    _drivesInProgress.RemoveAll(d => string.Equals(d.Name, x.Item1.Name, StringComparison.CurrentCultureIgnoreCase));
                    Console.WriteLine("Tanks for your confirmation and see you soon :D");
                }

                if (_errorQueue.TryDequeue(out var error))
                {
                    var x = error ?? null;
                    Console.WriteLine($"Something happened to '{x.Item1.VolumeLabel}', Name: '{x.Item1.Name}' at location '{x.Item2}'");
                    Console.WriteLine(x.Item3);
                    Console.Write("Please remove Drive and press any key to confirm.");
                    _synth.Speak("Error! Error! Please confirm you fagot.");
                    Console.Beep();
                    Console.ReadKey(intercept: true);
                    _drivesInProgress.RemoveAll(d => string.Equals(d.Name, x.Item1.Name, StringComparison.CurrentCultureIgnoreCase));
                    Console.WriteLine("Tanks for your confirmation please fix drive on another PC and then try again.");
                }

                if (_progressQueue.TryDequeue(out var progress))
                {
                    var x = progress ?? null;
                    Console.WriteLine($"Progress update: {progress.Item3}% '{x.Item1.VolumeLabel}', Name: '{x.Item1.Name}', Location '{x.Item2} ");
                }

                Thread.Sleep(100);
            }
        }
Пример #6
0
        public void Test_AlphaFS___AnalyzeSecurity_LocalAcessShouldNotExist()
        {
            string testDir = GetTempDirectoryName();

            SetSecuritySystem(testDir);
            var dirsec = new DirectoryInfo(testDir + @"\inherited").GetAccessControl();
            AuthorizationRuleCollection accessRules = dirsec.GetAccessRules(true, true, targetType: typeof(SecurityIdentifier));

            Assert.IsFalse(HasLocalAces(accessRules), "local access rules found");
        }
Пример #7
0
        private static int GetDepth(DirectoryInfo di)
        {
            int depth  = 0;
            var parent = di.Parent;

            while (parent != null)
            {
                depth++;
                parent = parent.Parent;
            }
            return(depth);
        }
Пример #8
0
 protected void DeleteOrRecycleFolder(DirectoryInfo di)
 {
     if (di == null)
     {
         return;
     }
     if (_tidyup.DeleteEmptyIsRecycle)
     {
         Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(di.FullName, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin);
     }
     else
     {
         di.Delete();
     }
 }
Пример #9
0
        public static bool Same(DirectoryInfo a, DirectoryInfo b)
        {
            string n1 = a.FullName;
            string n2 = b.FullName;

            if (!n1.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                n1 = n1 + Path.DirectorySeparatorChar;
            }
            if (!n2.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                n2 = n2 + Path.DirectorySeparatorChar;
            }

            return(String.Compare(n1, n2, true) == 0); // true->ignore case
        }
Пример #10
0
 private void lvFMNewShows_DragDrop(object _, [NotNull] DragEventArgs e)
 {
     string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
     foreach (string path in files)
     {
         try
         {
             DirectoryInfo di = new DirectoryInfo(path);
             if (di.Exists)
             {
                 engine.CheckFolderForShows(di, true, true, true);
                 FillNewShowList(true);
             }
         }
         catch
         {
             // ignored
         }
     }
 }
Пример #11
0
 private void AddDraggedFiles([NotNull] DragEventArgs e, List <string> strings)
 {
     string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
     foreach (string path in files)
     {
         try
         {
             DirectoryInfo di = new DirectoryInfo(path);
             if (di.Exists)
             {
                 strings.Add(path.ToLower());
             }
         }
         catch
         {
             // ignored
         }
     }
     mDoc.SetDirty();
     FillFolderStringLists();
 }
Пример #12
0
        private static bool CopyFile(USNJournalSyncLog syncLog, SyncMountpoint syncFrom)
        {
            logger.Info($"[{syncLog.Id}] [C] {syncLog.Action.RelativePath}");

            var copyAction = syncLog.Action as UpdateAction;

            var publicPath   = syncFrom.Mountpoint.Reference.PublicPath;
            var relativePath = copyAction.RelativePath;

            if (publicPath == null)
            {
                throw new NullReferenceException("publicPath");
            }
            if (relativePath == null)
            {
                throw new NullReferenceException("relativePath");
            }

            var    destination = Path.Get(syncFrom.Path, relativePath);
            string tempPath    = Path.Get(syncFrom.Path, ".proximaTemp.", "toCopy", syncLog.Id).FullPath;
            var    source      = Path.Get(publicPath, relativePath);

            if (source.IsDirectory)
            {
                DirectoryInfo sourceInfo = new DirectoryInfo(source.FullPath);
                DirectoryInfo tempInfo   = new DirectoryInfo(tempPath);
                DirectoryInfo destInfo   = new DirectoryInfo(destination.FullPath);
                sourceInfo.CopyTo(tempInfo.FullName);
                tempInfo.MoveTo(destInfo.FullName);
            }
            else
            {
                source.Copy(tempPath);
                FileInfo tempInfo = new FileInfo(tempPath);
                tempInfo.MoveTo(destination.FullPath, MoveOptions.ReplaceExisting);
            }

            return(true);
        }
Пример #13
0
        private static void DeleteDirectory(string path)
        {
            Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
            .DoProgress("Cleaning VFS Files", file =>
            {
                try
                {
                    var fi         = new FileInfo(file);
                    fi.Attributes &= ~FileAttributes.ReadOnly;
                    File.Delete(file);
                }
                catch (Exception ex)
                {
                    Utils.Log(ex.ToString());
                }
            });

            Directory.EnumerateDirectories(path, DirectoryEnumerationOptions.Recursive)
            .OrderByDescending(d => d.Length)
            .DoProgress("Cleaning VFS Folders", folder =>
            {
                try
                {
                    if (!Directory.Exists(folder))
                    {
                        return;
                    }
                    var di         = new DirectoryInfo(folder);
                    di.Attributes &= ~FileAttributes.ReadOnly;
                    Directory.Delete(path, true);
                }
                catch (Exception ex)
                {
                    Utils.Log(ex.ToString());
                }
            });
        }
Пример #14
0
      private static void DumpClassDirectoryInfo(bool isLocal)
      {
         #region Setup

         Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network);
         string tempPath = Path.Combine(Path.GetTempPath(), "DirectoryInfo()-" + Path.GetRandomFileName());
         if (!isLocal) tempPath = Path.LocalToUnc(tempPath);

         int expectedLastError;
         string expectedException;

         string nonExistingDirectory = SysRoot32 + @"\NonExistingDirectory-" + Path.GetRandomFileName();
         if (!isLocal) nonExistingDirectory = Path.LocalToUnc(nonExistingDirectory);

         string sysDrive = SysDrive;
         if (!isLocal) sysDrive = Path.LocalToUnc(sysDrive);

         string sysRoot = SysRoot;
         if (!isLocal) sysRoot = Path.LocalToUnc(sysRoot);

         string letter = DriveInfo.GetFreeDriveLetter() + @":\";
         if (!isLocal) letter = Path.LocalToUnc(letter);

         #endregion // Setup

         #region NotSupportedException

         expectedLastError = (int) (isLocal ? Win32Errors.ERROR_ENVVAR_NOT_FOUND : Win32Errors.NERR_UseNotFound);
         expectedException = "System.NotSupportedException";
         bool exception = false;
         try
         {
            Console.WriteLine("\nCatch: [{0}]: The given path's format is not supported.", expectedException);

            string invalidPath = SysDrive + @"\:a";
            if (!isLocal) invalidPath = Path.LocalToUnc(invalidPath) + @":a";

            DirectoryInfo di = new DirectoryInfo(invalidPath);
         }
         catch (Exception ex)
         {
            // Not reliable.
            //var win32Error = new Win32Exception("", ex);
            //Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode));
            //Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError));

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


         #region Current Directory

         tempPath = Path.CurrentDirectoryPrefix;
         if (!isLocal) tempPath = Path.LocalToUnc(tempPath);

         Console.WriteLine("\nInput Directory Path (Current directory): [{0}]\n", tempPath);

         StopWatcher(true);
         System.IO.DirectoryInfo expected = new System.IO.DirectoryInfo(tempPath);
         Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", Reporter());

         StopWatcher(true);
         DirectoryInfo actual = new DirectoryInfo(tempPath);
         Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", Reporter());

         // Compare values of both instances.
         CompareDirectoryInfos(expected, actual);

         #endregion // Current Directory

         #region Non-Existing Directory

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

         StopWatcher(true);
         expected = new System.IO.DirectoryInfo(tempPath);
         Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", Reporter());

         StopWatcher(true);
         actual = new DirectoryInfo(tempPath);
         Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", Reporter());

         // Compare values of both instances.
         CompareDirectoryInfos(expected, actual);

         #endregion // Non-Existing Directory

         #region Existing Directory

         tempPath = Path.Combine(Path.GetTempPath(), "DirectoryInfo()-Directory-" + Path.GetRandomFileName());
         if (!isLocal) tempPath = Path.LocalToUnc(tempPath);

         try
         {
            Directory.CreateDirectory(tempPath);

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

            StopWatcher(true);
            expected = new System.IO.DirectoryInfo(tempPath);
            Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", Reporter());

            StopWatcher(true);
            actual = new DirectoryInfo(tempPath);
            Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", Reporter());

            // Compare values of both instances.
            CompareDirectoryInfos(expected, actual);
         }
         finally
         {
            Directory.Delete(tempPath);
            Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed.");
         }
         
         #endregion // Existing Directory

         #region Method .ToString()

         Console.WriteLine("\nMethod .ToString()");
         Console.WriteLine("Both strings should be the same.\n");

         expected = new System.IO.DirectoryInfo("ToString()-TestDirectory");
         actual = new DirectoryInfo("ToString()-TestDirectory");

         string expectedToString = expected.ToString();
         string actualToString = actual.ToString();

         Console.WriteLine("\tSystem.IO: [{0}]", expectedToString);
         Console.WriteLine("\tAlphaFS  : [{0}]", actualToString);

         Assert.AreEqual(expectedToString, actualToString, false);
         Console.WriteLine();

         #endregion Method .ToString()
      }
Пример #15
0
        public static IList <string> GetGitignoreDirectories(string path, bool recursive, bool followSymlinks)
        {
            if (File.Exists(Path.Combine(path, ".gitignore")))
            {
                return new List <string> {
                           path
                }
            }
            ;

            var fileOptions = baseFileOptions;

            if (recursive)
            {
                fileOptions |= DirectoryEnumerationOptions.Recursive;
            }
            if (followSymlinks)
            {
                fileOptions &= ~DirectoryEnumerationOptions.SkipReparsePoints;
            }

            List <string> dontRecurseBelow = new List <string>
            {
                @"C:\$Recycle.Bin"
            };

            foreach (var sf in new[]
            {
                Environment.SpecialFolder.Windows,
                Environment.SpecialFolder.ProgramFiles,
                Environment.SpecialFolder.ProgramFilesX86,
            })
            {
                string p = Environment.GetFolderPath(sf);
                if (!string.IsNullOrEmpty(p))
                {
                    dontRecurseBelow.Add(p);
                }
            }

            DirectoryEnumerationFilters fileFilters = new DirectoryEnumerationFilters
            {
                ErrorFilter = (errorCode, errorMessage, pathProcessed) =>
                {
                    logger.Error($"Find file error {errorCode}: {errorMessage} on {pathProcessed}");
                    return(true);
                },
                RecursionFilter = fsei =>
                {
                    if (Utils.CancelSearch)
                    {
                        throw new OperationCanceledException();
                    }

                    if (fsei.IsDirectory && dontRecurseBelow.Any(p => fsei.FullPath.StartsWith(p, true, CultureInfo.CurrentCulture)))
                    {
                        return(false);
                    }
                    return(true);
                },
                InclusionFilter = fsei =>
                {
                    if (Utils.CancelSearch)
                    {
                        throw new OperationCanceledException();
                    }

                    if (fsei.FileName == ".gitignore")
                    {
                        dontRecurseBelow.Add(Path.GetDirectoryName(fsei.FullPath));
                        return(true);
                    }
                    return(false);
                }
            };

            try
            {
                // search down subdirectories
                var list = Directory.EnumerateFiles(path, fileOptions, fileFilters, PathFormat.FullPath)
                           .Select(s => Path.GetDirectoryName(s)).ToList();

                if (list.Count == 0)
                {
                    // not found, search up the tree
                    DirectoryInfo di = new DirectoryInfo(path);
                    while (di.Parent != null)
                    {
                        if (File.Exists(Path.Combine(di.Parent.FullName, ".gitignore")))
                        {
                            list.Add(path);
                            break;
                        }

                        di = di.Parent;
                    }
                }

                return(list);
            }
            catch (OperationCanceledException)
            {
                return(new List <string>());
            }
        }
Пример #16
0
        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);
        }
Пример #17
0
        private object GetDeviceInfo(int type, int mode)
        {
            try
            {
                switch (type)
                {
                    #region Volume

                // VolumeInfo properties.
                case 0:
                    if (Utils.IsNullOrWhiteSpace(_volumeInfo.FullPath))
                    {
                        _volumeInfo.Refresh();
                    }

                    switch (mode)
                    {
                    case 0:
                        // IsVolume, VolumeInfo
                        return(_volumeInfo);

                    case 1:
                        // DriveFormat
                        return(_volumeInfo == null?DriveType.Unknown.ToString() : _volumeInfo.FileSystemName ?? DriveType.Unknown.ToString());

                    case 2:
                        // VolumeLabel
                        return(_volumeInfo == null ? string.Empty : _volumeInfo.Name ?? string.Empty);
                    }
                    break;

                // Volume related.
                case 1:
                    switch (mode)
                    {
                    case 0:
                        // DosDeviceName

                        // Do not use ?? expression here.
                        if (_dosDeviceName == null)
                        {
                            _dosDeviceName = Volume.QueryDosDevice(Name).FirstOrDefault();
                        }
                        return(_dosDeviceName);
                    }
                    break;

                    #endregion // Volume

                    #region Drive

                // Drive related.
                case 2:
                    switch (mode)
                    {
                    case 0:
                        // DriveType
                        // Do not use ?? expression here.
                        if (_driveType == null)
                        {
                            _driveType = Volume.GetDriveType(Name);
                        }
                        return(_driveType);

                    case 1:
                        // RootDirectory

                        // Do not use ?? expression here.
                        if (_rootDirectory == null)
                        {
                            _rootDirectory = new DirectoryInfo(null, Name, PathFormat.RelativePath);
                        }
                        return(_rootDirectory);
                    }
                    break;

                // DiskSpaceInfo related.
                case 3:
                    switch (mode)
                    {
                    case 0:
                        // AvailableFreeSpace, TotalFreeSpace, TotalSize, DiskSpaceInfo
                        if (!_initDsie)
                        {
                            _dsi.Refresh();
                            _initDsie = true;
                        }
                        break;
                    }
                    break;

                    #endregion // Drive
                }
            }
            catch
            {
            }

            return(type == 0 && mode > 0 ? string.Empty : null);
        }
Пример #18
0
        private void TransferItem(USNJournalSyncLog syncLog, SyncMountpoint syncFrom)
        {
            try
            {
                syncLog.ActionStartDate  = DateTime.Now;
                syncLog.ActionFinishDate = null;
                Singleton.Instance.Repository.Update(syncLog);

                bool successfull = false;

                if (syncLog.Action.GetType() == typeof(DeleteAction))
                {
                    var path = Path.Get(syncFrom.Path, syncLog.Action.RelativePath);

                    logger.Info($"[{syncLog.Id}] [D] " + path);

                    if (path.Exists)
                    {
                        var destinationPath = Path.Get(syncFrom.Path, ".proximaTemp.", "toDelete", syncLog.Id).FullPath;

                        if (syncLog.Action.IsDirectory)
                        {
                            DirectoryInfo info = new DirectoryInfo(path.FullPath);
                            info.MoveTo(destinationPath);
                            info.Delete(true, true);
                        }
                        else
                        {
                            FileInfo info = new FileInfo(path.FullPath);
                            info.MoveTo(destinationPath);
                            info.Delete();
                        }
                    }


                    successfull = true;
                }

                else if (syncLog.Action.GetType() == typeof(RenameAction))
                {
                    var renameAction = syncLog.Action as RenameAction;

                    logger.Info($"[{syncLog.Id}] [R] {renameAction.RenameFrom} to {renameAction.RelativePath}");

                    if (String.IsNullOrWhiteSpace(renameAction.RenameFrom))
                    {
                        CopyFile(syncLog, syncFrom);
                    }

                    string pathFrom = Path.Get(syncFrom.Path, renameAction.RenameFrom).FullPath;
                    string tempPath = Path.Get(syncFrom.Path, ".proximaTemp.", "toRename", syncLog.Id).FullPath;
                    string pathTo   = Path.Get(syncFrom.Path, renameAction.RelativePath).FullPath;

                    if (syncLog.Action.IsDirectory)
                    {
                        new DirectoryInfo(pathFrom).MoveTo(tempPath, MoveOptions.None);
                        new DirectoryInfo(tempPath).MoveTo(pathTo, MoveOptions.None);
                    }
                    else
                    {
                        Alphaleonis.Win32.Filesystem.File.Move(pathFrom, tempPath, MoveOptions.None);
                        Alphaleonis.Win32.Filesystem.File.Move(tempPath, pathTo, MoveOptions.None);
                        //new FileInfo(pathFrom).MoveTo(tempPath, MoveOptions.WriteThrough);
                        //new FileInfo(tempPath).MoveTo(pathTo, MoveOptions.WriteThrough);
                    }

                    successfull = true;
                }
                else
                {
                    successfull = CopyFile(syncLog, syncFrom);
                }


                syncLog.ActionFinishDate = DateTime.Now;
                syncLog.Successfull      = successfull;
                Singleton.Instance.Repository.Update(syncLog);

                foreach (var error in Singleton.Instance.Repository.Many <Error>(f => f.SyncLog.Id == syncLog.Id))
                {
                    Singleton.Instance.Repository.Delete(error);
                }
            }
            catch (FileNotFoundException ex)
            {
                syncLog.RequiresManualIntervention = true;
                syncLog.ActionFinishDate           = DateTime.Now;
                Singleton.Instance.Repository.Update(syncLog);

                logger.Error(ex, "Error on item " + syncLog.Id);
                Error error = new Error();
                error.SyncLog   = syncLog;
                error.Exception = ex;
                error.ItemId    = syncLog.Id;
                error.Message   = ex.Message;
                Singleton.Instance.Repository.Add(error);
            }
            catch (Exception e)
            {
                syncLog.ActionFinishDate = DateTime.Now;
                Singleton.Instance.Repository.Update(syncLog);

                logger.Error(e, "Error on item " + syncLog.Id);
                Error error = new Error();
                error.SyncLog   = syncLog;
                error.Exception = e;
                error.ItemId    = syncLog.Id;
                error.Message   = e.Message;
                Singleton.Instance.Repository.Add(error);
            }
        }
Пример #19
0
        private void FillPreview()
        {
            this.lvPreview.Items.Clear();
            if ((string.IsNullOrEmpty(this.txtFolder.Text)) || (!Directory.Exists(this.txtFolder.Text)))
            {
                this.txtFolder.BackColor = Helpers.WarningColor();
                return;
            }
            else
            {
                this.txtFolder.BackColor = System.Drawing.SystemColors.Window;
            }

            if (this.Grid1.RowsCount <= 1) // 1 for header
            {
                return;                    // empty
            }
            this.lvPreview.Enabled = true;

            List <FilenameProcessorRE> rel = new List <FilenameProcessorRE>();

            if (this.chkTestAll.Checked)
            {
                for (int i = 1; i < this.Grid1.RowsCount; i++)
                {
                    FilenameProcessorRE re = this.REForRow(i);
                    if (re != null)
                    {
                        rel.Add(re);
                    }
                }
            }
            else
            {
                int[] rowsIndex = this.Grid1.Selection.GetSelectionRegion().GetRowsIndex();
                if (rowsIndex.Length == 0)
                {
                    return;
                }

                FilenameProcessorRE re2 = this.REForRow(rowsIndex[0]);
                if (re2 != null)
                {
                    rel.Add(re2);
                }
                else
                {
                    return;
                }
            }

            this.lvPreview.BeginUpdate();
            DirectoryInfo d = new DirectoryInfo(this.txtFolder.Text);

            foreach (FileInfo fi in d.GetFiles())
            {
                int seas;
                int ep;

                if (!TVSettings.Instance.UsefulExtension(fi.Extension, true))
                {
                    continue; // move on
                }
                ShowItem     si  = this.cbShowList.SelectedIndex >= 0 ? this.SIL[this.cbShowList.SelectedIndex] : null;
                bool         r   = TVDoc.FindSeasEp(fi, out seas, out ep, si, rel, false);
                ListViewItem lvi = new ListViewItem();
                lvi.Text = fi.Name;
                lvi.SubItems.Add((seas == -1) ? "-" : seas.ToString());
                lvi.SubItems.Add((ep == -1) ? "-" : ep.ToString());
                if (!r)
                {
                    lvi.BackColor = Helpers.WarningColor();
                }
                this.lvPreview.Items.Add(lvi);
            }
            this.lvPreview.EndUpdate();
        }
Пример #20
0
        /// <summary>Shows the Object's available Properties and Values.</summary>
        private static void Dump(object obj, int width = -35, bool indent = false)
        {
            int          cnt      = 0;
            const string nulll    = "\t\tnull";
            string       template = "\t{0}#{1:000}\t{2, " + width + "} == \t[{3}]";

            if (obj == null)
            {
                Console.WriteLine(nulll);
                return;
            }

            Console.WriteLine("\n\t{0}Instance: [{1}]\n", indent ? "\t" : "", obj.GetType().FullName);

            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj).Sort().Cast <PropertyDescriptor>().Where(descriptor => descriptor != null))
            {
                string propValue;
                try
                {
                    object value = descriptor.GetValue(obj);
                    propValue = (value == null) ? "null" : value.ToString();
                }
                catch (Exception ex)
                {
                    // Please do tell, oneliner preferably.
                    propValue = ex.Message.Replace(Environment.NewLine, "  ");
                }


                switch (descriptor.Name)
                {
                case "Parent":
                    if (obj.GetType().Namespace.Equals("Alphaleonis.Win32.Filesystem", StringComparison.OrdinalIgnoreCase))
                    {
                        if (obj != null)
                        {
                            DirectoryInfo di = (DirectoryInfo)obj;
                            if (di != null)
                            {
                                propValue = di.Parent == null ? null : di.Parent.ToString();
                            }
                        }
                    }
                    break;

                case "Root":
                    if (obj.GetType().Namespace.Equals("Alphaleonis.Win32.Filesystem", StringComparison.OrdinalIgnoreCase))
                    {
                        if (obj != null)
                        {
                            DirectoryInfo di = (DirectoryInfo)obj;
                            if (di != null)
                            {
                                propValue = di.Root.ToString();
                            }
                        }
                    }
                    break;

                case "EntryInfo":
                    if (obj.GetType().Namespace.Equals("Alphaleonis.Win32.Filesystem", StringComparison.OrdinalIgnoreCase))
                    {
                        if (obj != null)
                        {
                            DirectoryInfo di = (DirectoryInfo)obj;
                            if (di != null && di.EntryInfo != null)
                            {
                                propValue = di.EntryInfo.FullPath;
                            }
                        }
                    }
                    break;
                }

                Console.WriteLine(template, indent ? "\t" : "", ++cnt, descriptor.Name, propValue);
            }
        }
Пример #21
0
 internal DirectoryLocalArticle(DirectoryInfo info)
     : base()
 {
     Info = info;
 }
        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();
        }
Пример #23
0
      public void SetAccessControl()
      {
         Console.WriteLine("Directory.SetAccessControl()");

         //string path = SysDrive + @"\AlphaDirectory-" + Path.GetRandomFileName();
         string path = Path.Combine(Path.GetTempPath(), "Directory.GetAccessControl()-" + Path.GetRandomFileName());
         string pathAlpha = path;
         Directory.CreateDirectory(path);

         Console.WriteLine("\n\tDirectory: [{0}]", path);

         // Initial read.
         Console.WriteLine("\n\tInitial read.");
         DirectorySecurity dsAlpha = Directory.GetAccessControl(pathAlpha, AccessControlSections.Access);
         DirectorySecurity dsSystem = System.IO.Directory.GetAccessControl(path, AccessControlSections.Access);
         AuthorizationRuleCollection accessRulesSystem = dsSystem.GetAccessRules(true, true, typeof(NTAccount));
         StopWatcher(true);
         AuthorizationRuleCollection accessRulesAlpha = dsAlpha.GetAccessRules(true, true, typeof(NTAccount));
         Console.WriteLine("\t\tDirectory.GetAccessControl() rules found: [{0}]\n\t{1}", accessRulesAlpha.Count, Reporter());
         Assert.AreEqual(accessRulesSystem.Count, accessRulesAlpha.Count);

         // Sanity check.
         DumpAccessRules(1, dsSystem, dsAlpha);

         // 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.");
         dsAlpha.SetAccessRuleProtection(true, false);

         // Re-read, using instance methods.
         System.IO.DirectoryInfo diSystem = new System.IO.DirectoryInfo(Path.LocalToUnc(path));
         DirectoryInfo diAlpha = new DirectoryInfo(Path.LocalToUnc(path));

         dsSystem = diSystem.GetAccessControl(AccessControlSections.Access);
         dsAlpha = diAlpha.GetAccessControl(AccessControlSections.Access);

         // Sanity check.
         DumpAccessRules(2, dsSystem, dsAlpha);

         // Restore inherited properties.
         Console.WriteLine("\n\tRestore inherited properties and persist it.");
         dsAlpha.SetAccessRuleProtection(false, true);

         // Re-read.
         dsSystem = System.IO.Directory.GetAccessControl(path, AccessControlSections.Access);
         dsAlpha = Directory.GetAccessControl(pathAlpha, AccessControlSections.Access);

         // Sanity check.
         DumpAccessRules(3, dsSystem, dsAlpha);

         diAlpha.Delete();
         diAlpha.Refresh(); // Must Refresh() to get actual state.
         Assert.IsFalse(diAlpha.Exists);
      }
        /// <summary>
        /// This is the base copy/move function that I call when timing is not important. For me this would only run
        /// on our main network, and not at any facility site, but it would be really great for things like large
        /// path restores which will take a long time, and can function in a fire and forget kind of way.
        /// In all honestly the need for something like this is minuscule, since robocopy exists and it is much easier to implement
        /// But this would allow for easier use for end users, and in the end I wanted my app to be able to do both;
        /// Be a timer move/copy and a standard move/copy, so we can call a single app up to do multiple things.
        /// </summary>
        public async Task RunCopyorMove(String StartDirectory, String EndDirectory, PauseToken _pts, CancellationToken token, string logfile, int filesSkipped, int filesCopied, bool isRunning, long sum, long endsum, long progressvalue, long progressum)
        {
            if (!Alphaleonis.Win32.Filesystem.Directory.Exists(EndDirectory))
            {
                Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(EndDirectory);
            }
            if (!Alphaleonis.Win32.Filesystem.Directory.Exists(logfile))
            {
                Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(logfile);
            }
            List <String> FileNames    = new List <String>();
            List <String> SkippedFiles = new List <String>();
            List <String> ExtraFiles   = new List <String>();

            Alphaleonis.Win32.Filesystem.DirectoryInfo SrcDirct  = new Alphaleonis.Win32.Filesystem.DirectoryInfo(StartDirectory);
            Alphaleonis.Win32.Filesystem.DirectoryInfo DestDirct = new Alphaleonis.Win32.Filesystem.DirectoryInfo(EndDirectory);

            IEnumerable <Alphaleonis.Win32.Filesystem.FileInfo> srclist  = SrcDirct.EnumerateFiles("*", SearchOption.AllDirectories);
            IEnumerable <Alphaleonis.Win32.Filesystem.FileInfo> destlist = DestDirct.EnumerateFiles("*", SearchOption.AllDirectories);

            FileCompare myCompare = new FileCompare();

            var destListOnly = (from file in destlist select file).Except(srclist, myCompare);
            var destListLen  = destlist.Intersect(srclist, myCompare);
            var srcListOnly  = (from file in srclist select file).Except(destlist, myCompare);

            try
            {
                ///This warning is nice to have so the user does not accidentally do a move and not realize until it is too late.
                ///This could possibly be a message-box if you are really concered.
                if (checkBox2.Checked)
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        listBox1.Items.Add("This will delete the source path. If you did not intend that please hit Stop Copy");
                        listBox1.TopIndex = listBox1.Items.Count - 1;
                    });
                }

                var filecompare = Task.Run(async() =>
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        label7.Text       = "Getting Files Please wait";
                        listBox1.TopIndex = listBox1.Items.Count - 1;
                    });
                    if (_pts.IsPaused)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            listBox1.Items.Add("Paused");
                            listBox1.TopIndex = listBox1.Items.Count - 1;
                        });
                    }
                    else
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            listBox1.Items.Add("Not paused");
                            listBox1.TopIndex = listBox1.Items.Count - 1;
                        });
                    }

                    foreach (var v in destListOnly)
                    {
                        await _pts.WaitWhilePausedAsync();
                        extraFiles++;
                        this.Invoke((MethodInvoker) delegate
                        {
                            listBox1.Items.Add("Extra File " + v.FullName);
                            listBox1.TopIndex = listBox1.Items.Count - 1;
                        });
                        ExtraFiles.Add(v.FullName);
                    }
                    foreach (var v in srcListOnly)
                    {
                        await _pts.WaitWhilePausedAsync();
                        sum += v.Length;
                    }
                    foreach (var v in destListLen)
                    {
                        await _pts.WaitWhilePausedAsync();
                        filesSkipped++;
                        files--;
                        this.Invoke((MethodInvoker) delegate
                        {
                            listBox1.Items.Add("Skipped File " + v.FullName);
                            listBox1.TopIndex = listBox1.Items.Count - 1;
                        });
                        SkippedFiles.Add(v.FullName);
                        sum += v.Length;
                    }
                    this.Invoke((MethodInvoker) delegate
                    {
                        label5.Text = "Files Skipped " + filesSkipped + " Extra Files " + extraFiles;
                    });
                });
                await filecompare;
                ///Get the total number of files, and their size. Do note this will take a really long time.
                ///Which is why I left it off the After6 run, because those are usually very large moves.
                ///If you are talking 100s of gigs or even coming close to TB, it would eclipse the timers
                ///trying to get the info.
                var amountcopied = Task.Run(() =>
                {
                    var existingFiles = Alphaleonis.Win32.Filesystem.Directory.GetFiles(EndDirectory, "*", SearchOption.AllDirectories);
                    var existingRoot  = Alphaleonis.Win32.Filesystem.Directory.GetFiles(EndDirectory);

                    files += Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(StartDirectory, "*", SearchOption.AllDirectories).Count();
                    while (isRunning == true)
                    {
                        float secelasped  = ((float)sw.ElapsedMilliseconds / 1000);
                        float secleft     = (int)Math.Ceiling((secelasped / endsum) * (sum - endsum));
                        TimeSpan lefttime = TimeSpan.FromSeconds(secleft);
                        if (sum > Int32.MaxValue)
                        {
                            progressum    = sum / 1024;
                            progressvalue = endsum / 1024;
                        }
                        else
                        {
                            progressum    = sum;
                            progressvalue = endsum;
                        }
                        if (endsum > Int32.MaxValue)
                        {
                            progressvalue = endsum / 1024;
                            progressum    = sum / 1024;
                        }
                        else
                        {
                            progressum    = sum;
                            progressvalue = endsum;
                        }

                        this.Invoke((MethodInvoker) delegate
                        {
                            progressBar1.Style   = System.Windows.Forms.ProgressBarStyle.Continuous;
                            progressBar1.Minimum = 0;
                            progressBar1.Maximum = Convert.ToInt32(progressum);

                            progressBar1.Value = Convert.ToInt32(progressvalue);
                            label9.Text        = "Speed: " + (endsum / 1024d / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00") + " mb/s";
                            if (sum > 1024 && sum < 1048576)
                            {
                                label6.Text = "Amount copied  " + ((endsum / 1024d)).ToString("0.00") + "/" + ((sum / 1024d)).ToString("0.00") + " KB";
                            }
                            else if (sum > 1048576 && sum < 1073741824)
                            {
                                label6.Text = "Amount copied  " + ((endsum / 1024d) / 1024d).ToString("0.00") + "/" + ((sum / 1024d) / 1024d).ToString("0.00") + " MB";
                            }
                            else if (sum > 1073741824)
                            {
                                label6.Text = "Amount copied  " + (((endsum / 1024d) / 1024d) / 1024d).ToString("0.00") + "/" + (((sum / 1024d) / 1024d) / 1024d).ToString("0.00") + " GB";
                            }
                            label4.Text = "Files to Copy " + (files - filesCopied) + " Files Copied " + (filesCopied);
                            //label10.Text = "Files Copied " + (filesCopied);
                            label8.Text = "Time Remaning " + lefttime.ToString();
                            label7.Text = "Percent done " + ((100 * endsum / sum)).ToString() + "%";
                        });
                    }
                    if (isRunning == false)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            label7.Text = "";
                        });
                    }
                });
                var moveTask = Task.Run(async() =>
                {
                    sw.Start();

                    ///Note, this only works for sub directories, and will not copy over root contents, the next foreach loop takes care of that.
                    ///This is also wrapped in the same task, so it will do the sub first, then the root, and run it both on the same thread.
                    foreach (string dirPath in Alphaleonis.Win32.Filesystem.Directory.EnumerateDirectories(StartDirectory, "*", SearchOption.AllDirectories))
                    {
                        ///I initially did this with a DirectoryInfo and Alphaleonis.Win32.Filesystem.FileInfo, inplace of the style I did now. But this had a weird outcome
                        ///Where a subdir folder would be created, but the files would be copied to root. Doing it this way works
                        Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(dirPath.Replace(StartDirectory, EndDirectory));

                        foreach (string filename in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(dirPath))
                        {
                            try
                            {
                                using (FileStream SourceStream = Alphaleonis.Win32.Filesystem.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                                {
                                    using (FileStream DestinationStream = Alphaleonis.Win32.Filesystem.File.Open(filename.Replace(StartDirectory, EndDirectory), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                                    {
                                        await _pts.WaitWhilePausedAsync();
                                        string source      = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(SourceStream.SafeFileHandle);
                                        string destination = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(DestinationStream.SafeFileHandle);
                                        ///Check if the length match (since the file is created above)
                                        ///If the length is not right, it restarts the copy (meaning if stopped in the middle of copying it will
                                        ///start at the beginning rather than the same byte [TODO: Make it start the previous byte])
                                        ///Else it closes the current stream, and displays it already exists. Because of the foreach
                                        ///It will recursively start a new stream with the next file
                                        if (Alphaleonis.Win32.Filesystem.File.Exists(destination) && DestinationStream.Length == SourceStream.Length)
                                        {
                                            this.Invoke((MethodInvoker) delegate
                                            {
                                                listBox1.Items.Add("Skipping files. Please wait");
                                                listBox1.TopIndex = listBox1.Items.Count - 1;
                                            });
                                            //filesSkipped++;
                                            //files--;
                                            endsum += DestinationStream.Length;
                                            //SkippedFiles.Add(destination);
                                            DestinationStream.Close();
                                            SourceStream.Close();
                                        }
                                        else if (Alphaleonis.Win32.Filesystem.File.Exists(source) && DestinationStream.Length != SourceStream.Length)
                                        {
                                            this.Invoke((MethodInvoker) delegate
                                            {
                                                listBox1.Items.Add("Starting Copy of  " + source);
                                                listBox1.TopIndex = listBox1.Items.Count - 1;
                                            });
                                            await SourceStream.CopyToAsync(DestinationStream, 262144, token);
                                            this.Invoke((MethodInvoker) delegate
                                            {
                                                listBox1.Items.Add("Finished Copying  " + destination);
                                                listBox1.TopIndex = listBox1.Items.Count - 1;
                                            });
                                            filesCopied++;
                                            FileNames.Add(destination);
                                            endsum += DestinationStream.Length;
                                        }

                                        token.ThrowIfCancellationRequested();
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                this.Invoke((MethodInvoker) delegate
                                {
                                    listBox1.Items.Add(ex);
                                    listBox1.Items.Add("File move (subdir) date caused it");
                                });
                                throw;
                            }
                        }
                    }
                    foreach (string filename in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(StartDirectory))
                    {
                        try
                        {
                            using (FileStream SourceStream = Alphaleonis.Win32.Filesystem.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                using (FileStream DestinationStream = Alphaleonis.Win32.Filesystem.File.Open(EndDirectory + filename.Substring(filename.LastIndexOf('\\')), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                                {
                                    await _pts.WaitWhilePausedAsync();
                                    string source      = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(SourceStream.SafeFileHandle);
                                    string destination = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(DestinationStream.SafeFileHandle);
                                    if (Alphaleonis.Win32.Filesystem.File.Exists(destination) && DestinationStream.Length == SourceStream.Length)
                                    {
                                        this.Invoke((MethodInvoker) delegate
                                        {
                                            listBox1.Items.Add("Skipping files. Please wait");
                                            listBox1.TopIndex = listBox1.Items.Count - 1;
                                        });
                                        //filesSkipped++;
                                        //files--;
                                        endsum += DestinationStream.Length;
                                        //SkippedFiles.Add(destination);
                                        DestinationStream.Close();
                                        SourceStream.Close();
                                    }
                                    else if (Alphaleonis.Win32.Filesystem.File.Exists(source) && DestinationStream.Length != SourceStream.Length)
                                    {
                                        this.Invoke((MethodInvoker) delegate
                                        {
                                            listBox1.Items.Add("Starting Copy of  " + source);
                                            listBox1.TopIndex = listBox1.Items.Count - 1;
                                        });
                                        await SourceStream.CopyToAsync(DestinationStream, 262144, token);
                                        this.Invoke((MethodInvoker) delegate
                                        {
                                            listBox1.Items.Add("Finished Copying  " + destination);
                                            listBox1.TopIndex = listBox1.Items.Count - 1;
                                        });
                                        filesCopied++;
                                        FileNames.Add(destination);
                                        endsum += DestinationStream.Length;
                                    }
                                    token.ThrowIfCancellationRequested();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            this.Invoke((MethodInvoker) delegate
                            {
                                listBox1.Items.Add(ex);
                                listBox1.Items.Add("File move (rootdir) date caused it");
                                listBox1.TopIndex = listBox1.Items.Count - 1;
                            });
                            throw;
                        }
                    }
                });
                await moveTask;
                var   modify = Task.Run(async() =>
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        listBox1.Items.Add("Setting modify and change date. Please wait");
                        listBox1.TopIndex = listBox1.Items.Count - 1;
                    });

                    foreach (string filename in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(StartDirectory))
                    {
                        try
                        {
                            using (FileStream SourceStream = Alphaleonis.Win32.Filesystem.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                using (FileStream DestinationStream = Alphaleonis.Win32.Filesystem.File.Open(EndDirectory + filename.Substring(filename.LastIndexOf('\\')), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                                {
                                    await _pts.WaitWhilePausedAsync();
                                    string source      = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(SourceStream.SafeFileHandle);
                                    string destination = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(DestinationStream.SafeFileHandle);
                                    this.Invoke((MethodInvoker) delegate
                                    {
                                        listBox1.Items.Add("Changing Modify, Creation, and Change date for " + destination);
                                        listBox1.TopIndex = listBox1.Items.Count - 1;
                                    });
                                    DateTime dt = Alphaleonis.Win32.Filesystem.File.GetCreationTime(source);
                                    DateTime at = Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(source);
                                    DateTime wt = Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(source);
                                    Alphaleonis.Win32.Filesystem.File.SetCreationTime(destination, dt);
                                    Alphaleonis.Win32.Filesystem.File.SetLastAccessTime(destination, at);
                                    Alphaleonis.Win32.Filesystem.File.SetLastWriteTime(destination, wt);
                                    this.Invoke((MethodInvoker) delegate
                                    {
                                        listBox1.Items.Add("Modify, Creation, and Change date set for " + destination);
                                        listBox1.TopIndex = listBox1.Items.Count - 1;
                                    });
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            this.Invoke((MethodInvoker) delegate
                            {
                                listBox1.Items.Add(ex);
                                listBox1.Items.Add("File modify date caused it");
                                listBox1.TopIndex = listBox1.Items.Count - 1;
                            });
                            throw;
                        }
                    }
                    foreach (string dirPath in Alphaleonis.Win32.Filesystem.Directory.EnumerateDirectories(StartDirectory, "*", SearchOption.AllDirectories))
                    {
                        foreach (string filename in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(dirPath))
                        {
                            try
                            {
                                using (FileStream SourceStream = Alphaleonis.Win32.Filesystem.File.Open(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                                {
                                    using (FileStream DestinationStream = Alphaleonis.Win32.Filesystem.File.Open(filename.Replace(StartDirectory, EndDirectory), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                                    {
                                        await _pts.WaitWhilePausedAsync();
                                        string source      = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(SourceStream.SafeFileHandle);
                                        string destination = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(DestinationStream.SafeFileHandle);
                                        this.Invoke((MethodInvoker) delegate
                                        {
                                            listBox1.Items.Add("Changing Modify, Creation, and Change date for " + destination);
                                            listBox1.TopIndex = listBox1.Items.Count - 1;
                                        });
                                        DateTime dt = Alphaleonis.Win32.Filesystem.File.GetCreationTime(source);
                                        DateTime at = Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(source);
                                        DateTime wt = Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(source);
                                        Alphaleonis.Win32.Filesystem.File.SetCreationTime(destination, dt);
                                        Alphaleonis.Win32.Filesystem.File.SetLastAccessTime(destination, at);
                                        Alphaleonis.Win32.Filesystem.File.SetLastWriteTime(destination, wt);
                                        this.Invoke((MethodInvoker) delegate
                                        {
                                            listBox1.Items.Add("Modify, Creation, and Change date set for " + destination);
                                            listBox1.TopIndex = listBox1.Items.Count - 1;
                                        });
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                this.Invoke((MethodInvoker) delegate
                                {
                                    listBox1.Items.Add(ex);
                                    listBox1.Items.Add("File modify date caused it");
                                    listBox1.TopIndex = listBox1.Items.Count - 1;
                                });
                                throw;
                            }
                        }
                    }
                    DateTime dirt = new DateTime();
                    DateTime dira = new DateTime();
                    DateTime dirw = new DateTime();
                    foreach (string dirPath in Alphaleonis.Win32.Filesystem.Directory.GetDirectories(StartDirectory, "*", SearchOption.AllDirectories))
                    {
                        dirt = Alphaleonis.Win32.Filesystem.Directory.GetCreationTime(dirPath);
                        dira = Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTime(dirPath);
                        dirw = Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTime(dirPath);
                    }
                    foreach (string endDirPath in Alphaleonis.Win32.Filesystem.Directory.EnumerateDirectories(EndDirectory, "*", SearchOption.AllDirectories))
                    {
                        try
                        {
                            await _pts.WaitWhilePausedAsync();
                            this.Invoke((MethodInvoker) delegate
                            {
                                listBox1.Items.Add("Changing Modify, Creation, and Change date for " + endDirPath);
                                listBox1.TopIndex = listBox1.Items.Count - 1;
                            });
                            Alphaleonis.Win32.Filesystem.Directory.SetCreationTime(endDirPath, dirt);
                            Alphaleonis.Win32.Filesystem.Directory.SetLastAccessTime(endDirPath, dira);
                            Alphaleonis.Win32.Filesystem.Directory.SetLastWriteTime(endDirPath, dirw);
                            this.Invoke((MethodInvoker) delegate
                            {
                                listBox1.Items.Add("Modify, Creation, and Change date set for " + endDirPath);
                                listBox1.TopIndex = listBox1.Items.Count - 1;
                            });
                        }
                        catch (Exception ex)
                        {
                            this.Invoke((MethodInvoker) delegate
                            {
                                listBox1.Items.Add(ex);
                                listBox1.Items.Add("Directory modify date caused it");
                                listBox1.TopIndex = listBox1.Items.Count - 1;
                            });
                            throw;
                        }
                    }
                });
                await modify;
                if (checkBox2.Checked)
                {
                    if (Alphaleonis.Win32.Filesystem.Directory.Exists(SrcPath.Text))
                    {
                        try
                        {
                            this.Invoke((MethodInvoker) delegate
                            {
                                listBox1.Items.Add("Deleting the source directory, please wait.");
                                listBox1.TopIndex = listBox1.Items.Count - 1;
                            });

                            var folderdelete = Task.Run(async() =>
                            {
                                Alphaleonis.Win32.Filesystem.Directory.Delete(SrcPath.Text, true);
                            }, token);
                            await folderdelete;
                        }

                        catch (System.IO.IOException ex)
                        {
                            this.Invoke((MethodInvoker) delegate
                            {
                                listBox1.Items.Add(ex);
                                listBox1.Items.Add("Folder Delete caused it");
                                listBox1.TopIndex = listBox1.Items.Count - 1;
                            });
                            throw;
                        }
                    }
                    this.Invoke((MethodInvoker) delegate
                    {
                        listBox1.Items.Add("**********File Move has Completed!*****");
                        listBox1.TopIndex = listBox1.Items.Count - 1;
                    });
                    PrepareControlsForCancel();
                }
                else
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        listBox1.Items.Add("**********File Copy has Completed!*****");
                        listBox1.TopIndex = listBox1.Items.Count - 1;
                    });
                    PrepareControlsForCancel();
                }
            }
            catch (OperationCanceledException)
            {
                this.Invoke((MethodInvoker) delegate
                {
                    listBox1.Items.Add("Cancelled.");
                    listBox1.TopIndex = listBox1.Items.Count - 1;
                });
                PrepareControlsForCancel();
            }
            catch (Exception ex)
            {
                this.Invoke((MethodInvoker) delegate
                {
                    listBox1.Items.Add(ex);
                });
                ErrorLog(ex, logfile, StartDirectory);
            }
            FileLog(StartDirectory, logfile, FileNames, SkippedFiles, filesCopied, endsum, filesSkipped, extraFiles, ExtraFiles);
        }
Пример #25
0
      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();
      }
Пример #26
0
      private void DumpEnumerateFileSystemEntries(bool isLocal)
      {
         #region Setup

         Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network);

         int cnt = 0;
         string searchPattern = Path.WildcardStarMatchAll;
         SearchOption searchOption = SearchOption.TopDirectoryOnly;

         bool exception;
         int expectedLastError;
         string expectedException;

         string random = Path.GetRandomFileName();
         string folderSource = @"folder-source-" + random;

         string originalLetter = DriveInfo.GetFreeDriveLetter() + @":";
         string letter = originalLetter + @"\";

         #endregion //Setup

         #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}]: Path is invalid, such as referring to an unmapped drive.", expectedException);

            string nonExistingPath = letter + folderSource;
            if (!isLocal) nonExistingPath = Path.LocalToUnc(nonExistingPath);

            new DirectoryInfo(nonExistingPath).EnumerateFileSystemInfos().Any();
         }
         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));
            Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError));

            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 IOException

         string tempPath = Path.GetTempPath("Directory.EnumerateFileSystemEntries-file-" + Path.GetRandomFileName());
         if (!isLocal) tempPath = Path.LocalToUnc(tempPath);

         try
         {
            using (File.Create(tempPath)) { }

            expectedLastError = (int)Win32Errors.ERROR_DIRECTORY;
            expectedException = "System.IO.IOException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: Path is a file name.", expectedException);

               new DirectoryInfo(tempPath).EnumerateFileSystemInfos().Any();
            }
            catch (IOException 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);
         }
         finally
         {
            File.Delete(tempPath);
            Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed.");
            Console.WriteLine();
         }

         #endregion // IOException

         #region UnauthorizedAccessException

         tempPath = Path.Combine(SysRoot, "CSC");
         if (!isLocal) tempPath = Path.LocalToUnc(tempPath);

         var di = new DirectoryInfo(tempPath);
         if (di.Exists)
         {
            expectedLastError = (int)Win32Errors.ERROR_ACCESS_DENIED;
            expectedException = "System.UnauthorizedAccessException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: The caller does not have the required permission.", expectedException);

               di.EnumerateFileSystemInfos(searchPattern, SearchOption.AllDirectories).All(o => o.Exists);
            }
            catch (UnauthorizedAccessException ex)
            {
               var win32Error = new Win32Exception("", ex);
               Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode));
               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();
         }

         #endregion // UnauthorizedAccessException

         string path = isLocal ? SysRoot : Path.LocalToUnc(SysRoot);

         Console.WriteLine("\nInput Directory Path: [{0}]\n", path);
         Console.WriteLine("\tEnumerate file system entries, using \"SearchOption.{0}\"\n", searchOption);

         StopWatcher(true);
         foreach (FileSystemInfo fsi in new DirectoryInfo(path).EnumerateFileSystemInfos(searchPattern, searchOption))
         {
            Console.WriteLine("\t#{0:000}\t[{1}]", ++cnt, fsi.FullName);

            // Issue #21601: OverflowException when accessing EntryInfo.
            // (Actually only for DirectoryInfo() and FileInfo())
            var isMountPoint = fsi.EntryInfo.IsMountPoint;
         }

         Console.WriteLine();
         Console.WriteLine(Reporter());
         Assert.IsTrue(cnt > 0, "Nothing was enumerated.");
         Console.WriteLine();


         cnt = 0;
         searchPattern = @"*e*e*";
         Console.WriteLine("\tsearchPattern: [{0}]\n", searchPattern);
         StopWatcher(true);
         foreach (FileSystemInfo fsi in new DirectoryInfo(path).EnumerateDirectories(searchPattern, searchOption))
         {
            Console.WriteLine("\t#{0:000}\t[{1}]", ++cnt, fsi.FullName);

            // Issue #21601: OverflowException when accessing EntryInfo.
            var isMountPoint = fsi.EntryInfo.IsMountPoint;

            Assert.IsTrue(fsi.EntryInfo.IsDirectory || !fsi.EntryInfo.IsDirectory);
         }

         Console.WriteLine();
         Console.WriteLine(Reporter());
         Assert.IsTrue(cnt > 0, "Nothing was enumerated.");
         Console.WriteLine();
      }
Пример #27
0
        protected void DoTidyup(DirectoryInfo di)
        {
#if DEBUG
            Debug.Assert(this._tidyup != null);
            Debug.Assert(this._tidyup.DeleteEmpty);
#else
            if (_tidyup == null || !_tidyup.DeleteEmpty)
            {
                return;
            }
#endif
            // See if we should now delete the folder we just moved that file from.
            if (di == null)
            {
                return;
            }

            //if there are sub-directories then we shouldn't remove this one
            if (di.GetDirectories().Length > 0)
            {
                return;
            }

            //if the directory is the root download folder do not delete
            if (TVSettings.Instance.MonitorFolders && TVSettings.Instance.SearchFoldersNames.Contains(di.FullName))
            {
                return;
            }

            // Do not delete any monitor folders either
            if (TVSettings.Instance.MonitorFoldersNames.Contains(di.FullName))
            {
                return;
            }


            FileInfo[] files = di.GetFiles();
            if (files.Length == 0)
            {
                // its empty, so just delete it
                di.Delete();
                return;
            }


            if (_tidyup.EmptyIgnoreExtensions && !_tidyup.EmptyIgnoreWords)
            {
                return; // nope
            }
            foreach (FileInfo fi in files)
            {
                bool okToDelete = _tidyup.EmptyIgnoreExtensions &&
                                  Array.FindIndex(_tidyup.EmptyIgnoreExtensionsArray, x => x == fi.Extension) != -1;

                if (okToDelete)
                {
                    continue; // onto the next file
                }
                // look in the filename
                if (_tidyup.EmptyIgnoreWordsArray.Any(word => fi.Name.Contains(word)))
                {
                    okToDelete = true;
                }

                if (!okToDelete)
                {
                    return;
                }
            }

            if (_tidyup.EmptyMaxSizeCheck)
            {
                // how many MB are we deleting?
                long totalBytes = files.Sum(fi => fi.Length);

                if (totalBytes / (1024 * 1024) > _tidyup.EmptyMaxSizeMB)
                {
                    return; // too much
                }
            }
            DeleteOrRecycleFolder(di);
        }
Пример #28
0
      private static void CompareDirectoryInfos(System.IO.DirectoryInfo expected, DirectoryInfo actual)
      {
         if (expected == null || actual == null)
            Assert.AreEqual(expected, actual, "Mismatch");

         Dump(expected, -17);
         Dump(actual, -17);
         

         int errorCnt = 0;
         int cnt = -1;
         while (cnt != 13)
         {
            cnt++;

            if (expected == null || actual == null)
               Assert.AreEqual(expected, actual, "One or both of the DirectoryInfo instances is/are null.");

            else
            {
               try
               {
                  // Compare values of both instances.
                  switch (cnt)
                  {
                     case 0: Assert.AreEqual(expected.Attributes, actual.Attributes, "Attributes AlphaFS != System.IO"); break;
                     case 1: Assert.AreEqual(expected.CreationTime, actual.CreationTime, "CreationTime AlphaFS != System.IO"); break;
                     case 2: Assert.AreEqual(expected.CreationTimeUtc, actual.CreationTimeUtc, "CreationTimeUtc AlphaFS != System.IO"); break;
                     case 3: Assert.AreEqual(expected.Exists, actual.Exists, "Exists AlphaFS != System.IO"); break;
                     case 4: Assert.AreEqual(expected.Extension, actual.Extension, "Extension AlphaFS != System.IO"); break;
                     case 5: Assert.AreEqual(expected.FullName, actual.FullName, "FullName AlphaFS != System.IO"); break;
                     case 6: Assert.AreEqual(expected.LastAccessTime, actual.LastAccessTime, "LastAccessTime AlphaFS != System.IO"); break;
                     case 7: Assert.AreEqual(expected.LastAccessTimeUtc, actual.LastAccessTimeUtc, "LastAccessTimeUtc AlphaFS != System.IO"); break;
                     case 8: Assert.AreEqual(expected.LastWriteTime, actual.LastWriteTime, "LastWriteTime AlphaFS != System.IO"); break;
                     case 9: Assert.AreEqual(expected.LastWriteTimeUtc, actual.LastWriteTimeUtc, "LastWriteTimeUtc AlphaFS != System.IO"); break;
                     case 10: Assert.AreEqual(expected.Name, actual.Name, "Name AlphaFS != System.IO"); break;

                     // Need .ToString() here since the object types are obviously not the same.
                     case 11: Assert.AreEqual(expected.Parent.ToString(), actual.Parent.ToString(), "Parent AlphaFS != System.IO"); break;
                     case 12: Assert.AreEqual(expected.Root.ToString(), actual.Root.ToString(), "Root AlphaFS != System.IO"); break;
                  }
               }
               catch (Exception ex)
               {
                  errorCnt++;
                  Console.WriteLine("\n\t\tProperty cnt #{0}\tCaught Exception: [{1}]", (cnt + 1), ex.Message.Replace(Environment.NewLine, "  "));
               }
            }
         }

         //Assert.IsTrue(errorCnt == 0, "\tEncountered: [{0}] DirectoryInfo Properties where AlphaFS != System.IO", errorCnt);
         Console.WriteLine();
      }
Пример #29
0
      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
      }
Пример #30
0
        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
        }
Пример #31
0
        public static IList <string> GetGitignoreDirectories(string path, bool recursive, bool followSymlinks)
        {
            if (File.Exists(Path.Combine(path, ".gitignore")))
            {
                return new List <string> {
                           path
                }
            }
            ;

            var fileOptions = baseFileOptions;

            if (recursive)
            {
                fileOptions |= DirectoryEnumerationOptions.Recursive;
            }
            if (followSymlinks)
            {
                fileOptions &= ~DirectoryEnumerationOptions.SkipReparsePoints;
            }

            List <string> dontRecurseBelow = new List <string>();

            DirectoryEnumerationFilters fileFilters = new DirectoryEnumerationFilters
            {
                ErrorFilter = (errorCode, errorMessage, pathProcessed) =>
                {
                    logger.Error($"Find file error {errorCode}: {errorMessage} on {pathProcessed}");
                    return(true);
                },
                RecursionFilter = fsei =>
                {
                    if (fsei.IsDirectory && dontRecurseBelow.Any(p => fsei.FullPath.StartsWith(p, StringComparison.CurrentCulture)))
                    {
                        return(false);
                    }
                    return(true);
                },
                InclusionFilter = fsei =>
                {
                    if (fsei.FileName == ".gitignore")
                    {
                        dontRecurseBelow.Add(Path.GetDirectoryName(fsei.FullPath));
                        return(true);
                    }
                    return(false);
                }
            };

            var list = Directory.EnumerateFiles(path, fileOptions, fileFilters, PathFormat.FullPath)
                       .Select(s => Path.GetDirectoryName(s)).ToList();

            if (list.Count == 0)
            {
                DirectoryInfo di = new DirectoryInfo(path);
                while (di.Parent != null)
                {
                    if (File.Exists(Path.Combine(di.Parent.FullName, ".gitignore")))
                    {
                        list.Add(path);
                        break;
                    }

                    di = di.Parent;
                }
            }

            return(list);
        }
Пример #32
0
      private void DumpCopy(bool isLocal)
      {
         #region Setup

         Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network);
         string path = isLocal ? SysRoot : Path.LocalToUnc(SysRoot);
         string tempPath = Path.GetTempPath("File-Copy-" + Path.GetRandomFileName());
         if (!isLocal) tempPath = Path.LocalToUnc(tempPath);

         bool exception;
         int expectedLastError;
         string expectedException;

         string fileSource = @"file-source-" + Path.GetRandomFileName() + ".exe";
         string fileDestination = @"file-destination-" + Path.GetRandomFileName() + ".exe";

         string folderSource = tempPath + @"\folder-source-" + Path.GetRandomFileName();
         string folderDestination = tempPath + @"\folder-destination-" + Path.GetRandomFileName();

         string fullPathSource = folderSource + @"\" + fileSource;
         string fullPathDestination = folderDestination + @"\" + fileDestination;
         if (!isLocal) fullPathSource = Path.LocalToUnc(fullPathSource);
         if (!isLocal) fullPathDestination = Path.LocalToUnc(fullPathDestination);

         DirectoryInfo dirInfo = new DirectoryInfo(folderDestination);

         #endregion // Setup

         try
         {
            #region UnauthorizedAccessException

            Directory.CreateDirectory(folderSource);
            Directory.CreateDirectory(folderDestination);

            DirectorySecurity dirSecurity;

            string user = (Environment.UserDomainName + @"\" + Environment.UserName).TrimStart('\\');

            // ╔═════════════╦═════════════╦═══════════════════════════════╦════════════════════════╦══════════════════╦═══════════════════════╦═════════════╦═════════════╗
            // ║             ║ folder only ║ folder, sub-folders and files ║ folder and sub-folders ║ folder and files ║ sub-folders and files ║ sub-folders ║    files    ║
            // ╠═════════════╬═════════════╬═══════════════════════════════╬════════════════════════╬══════════════════╬═══════════════════════╬═════════════╬═════════════╣
            // ║ Propagation ║ none        ║ none                          ║ none                   ║ none             ║ InheritOnly           ║ InheritOnly ║ InheritOnly ║
            // ║ Inheritance ║ none        ║ Container|Object              ║ Container              ║ Object           ║ Container|Object      ║ Container   ║ Object      ║
            // ╚═════════════╩═════════════╩═══════════════════════════════╩════════════════════════╩══════════════════╩═══════════════════════╩═════════════╩═════════════╝

            var rule = new FileSystemAccessRule(user, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny);

            expectedLastError = (int)Win32Errors.ERROR_ACCESS_DENIED;
            expectedException = "System.UnauthorizedAccessException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: The caller does not have the required permission.", expectedException);

               FileInfo fileInfo = new FileInfo(fullPathSource);
               using (StreamWriter sw = fileInfo.CreateText())
                  sw.WriteLine("MoveTo-TestFile");

               // Set DENY for current user.
               dirSecurity = dirInfo.GetAccessControl();
               dirSecurity.AddAccessRule(rule);
               dirInfo.SetAccessControl(dirSecurity);

               fileInfo.CopyTo(fullPathDestination);
            }
            catch (UnauthorizedAccessException ex)
            {
               Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError));

               exception = true;
               Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            catch (Exception ex)
            {
               Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            finally
            {
               // Remove DENY for current user.
               dirSecurity = dirInfo.GetAccessControl();
               dirSecurity.RemoveAccessRule(rule);
               dirInfo.SetAccessControl(dirSecurity, AccessControlSections.Access);

               Directory.Delete(tempPath, true, true);
            }
            Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
            Console.WriteLine();

            #endregion // UnauthorizedAccessException

            #region FileNotFoundException

            expectedLastError = (int)Win32Errors.ERROR_FILE_NOT_FOUND;
            expectedException = "System.IO.FileNotFoundException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: sourceFileName was not found.", expectedException);
               
               File.Copy(isLocal ? fileSource : Path.LocalToUnc(fileSource), isLocal ? fileDestination : Path.LocalToUnc(fileDestination));
            }
            catch (FileNotFoundException ex)
            {
               var win32Error = new Win32Exception("", ex);
               Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode));

               exception = true;
               Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            catch (Exception ex)
            {
               Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
            Console.WriteLine();

            #endregion // FileNotFoundException

            #region DirectoryNotFoundException

            expectedLastError = (int)Win32Errors.ERROR_PATH_NOT_FOUND;
            expectedException = "System.IO.DirectoryNotFoundException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: The path specified in sourceFileName or destFileName is invalid (for example, it is on an unmapped drive).", expectedException);
               
               File.Copy(fullPathSource, fullPathDestination);
            }
            catch (DirectoryNotFoundException ex)
            {
               var win32Error = new Win32Exception("", ex);
               Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode));

               exception = true;
               Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            catch (Exception ex)
            {
               Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));               
            }
            Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
            Console.WriteLine();

            #endregion // DirectoryNotFoundException

            #region IOException #1 (AlreadyExistsException)

            Directory.CreateDirectory(folderSource);
            Directory.CreateDirectory(folderDestination);
            using (File.Create(fullPathSource)) { }
            using (File.Create(fullPathDestination)) { }

            expectedLastError = (int)Win32Errors.ERROR_FILE_EXISTS;
            expectedException = "System.IO.IOException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: destFileName exists and overwrite is false.", expectedException);

               File.Copy(fullPathSource, fullPathDestination);
            }
            catch (AlreadyExistsException ex)
            {
               var win32Error = new Win32Exception("", ex);
               Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode));

               exception = true;
               Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            catch (Exception ex)
            {
               Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
            Console.WriteLine();

            Directory.Delete(folderSource, true);
            Directory.Delete(folderDestination, true);

            #endregion // IOException #1 (AlreadyExistsException)

            #region IOException #2

            string folderfileName = null;

            expectedLastError = (int)Win32Errors.ERROR_ACCESS_DENIED;
            expectedException = "System.IO.IOException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: A folder with the same name as the file exists.", expectedException);
               foreach (string file in Directory.EnumerateFiles(path))
               {
                  string newFile = Path.Combine(tempPath, Path.GetFileName(file, true));
                  folderfileName = newFile;

                  // Trigger the Exception.
                  Directory.CreateDirectory(folderfileName);

                  // true: overwrite existing.
                  File.Copy(file, folderfileName, true);
               }
            }
            catch (AlreadyExistsException ex)
            {
               var win32Error = new Win32Exception("", ex);
               Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode));

               exception = true;
               Directory.Delete(folderfileName);
               Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            catch (Exception ex)
            {
               Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
            Console.WriteLine();

            #endregion // IOException #2

            #region Copy

            Console.WriteLine("\nInput Directory Path: [{0}]\n", path);
            int cnt = 0;
            string readOnlySource = null;
            string readOnlyDestination = null;

            StopWatcher(true);
            foreach (string file in Directory.EnumerateFiles(path))
            {
               string newFile = Path.Combine(tempPath, Path.GetFileName(file, true));
               File.Copy(file, newFile);

               // Set the first file as read-only to trigger an Exception when copying again.
               if (cnt == 0)
               {
                  File.SetAttributes(newFile, FileAttributes.ReadOnly);
                  readOnlySource = file;
                  readOnlyDestination = newFile;
               }

               Console.WriteLine("\t#{0:000}\tCopied to: [{1}]", ++cnt, newFile);
               Assert.IsTrue(File.Exists(newFile));
            }
            Console.WriteLine("\n\tTotal Size: [{0}]{1}", Utils.UnitSizeToText(Directory.GetProperties(tempPath)["Size"]), Reporter());
            Console.WriteLine();

            #endregion // Copy

            #region Preserve Timestamps

            // Test preservation of timestamps.
            int seed = (int)DateTime.Now.Ticks & 0x0000FFFF;
            DateTime creationTime = new DateTime(new Random(seed).Next(1971, 2071), new Random(seed).Next(1, 12), new Random(seed).Next(1, 28), new Random(seed).Next(0, 23), new Random(seed).Next(0, 59), new Random(seed).Next(0, 59));
            seed += (int)DateTime.Now.Ticks & 0x0000FFFF;
            DateTime lastAccessTime = new DateTime(new Random(seed).Next(1971, 2071), new Random(seed).Next(1, 12), new Random(seed).Next(1, 28), new Random(seed).Next(0, 23), new Random(seed).Next(0, 59), new Random(seed).Next(0, 59));
            seed += (int)DateTime.Now.Ticks & 0x0000FFFF;
            DateTime lastWriteTime = new DateTime(new Random(seed).Next(1971, 2071), new Random(seed).Next(1, 12), new Random(seed).Next(1, 28), new Random(seed).Next(0, 23), new Random(seed).Next(0, 59), new Random(seed).Next(0, 59));

            string preservePath = Path.Combine(tempPath, "PreserveTimestamps");
            string preserveFile = Path.GetFileName(readOnlySource);
            string preserveReadOnlySource = Path.Combine(preservePath, preserveFile);

            Directory.CreateDirectory(preservePath);
            File.Copy(readOnlySource, preserveReadOnlySource);

            File.SetCreationTime(preserveReadOnlySource, creationTime);
            File.SetLastAccessTime(preserveReadOnlySource, lastAccessTime);
            File.SetLastWriteTime(preserveReadOnlySource, lastWriteTime);
            
            StopWatcher(true);

            // 3rd parameter CopyOptions.None: overwrite existing.
            // 4rd parameter true: preserve timestamps of source.
            File.Copy(preserveReadOnlySource, readOnlyDestination, CopyOptions.None, true);

            Console.WriteLine("\tFile copied.{0}", Reporter());

            Assert.IsTrue(File.Exists(preserveReadOnlySource));
            Assert.IsTrue(File.Exists(readOnlyDestination));

            Assert.AreEqual(File.GetCreationTime(readOnlyDestination), creationTime, "File CreationTime should match.");
            Assert.AreEqual(File.GetLastAccessTime(readOnlyDestination), lastAccessTime, "File LastAccessTime should match.");
            Assert.AreEqual(File.GetLastWriteTime(readOnlyDestination), lastWriteTime, "File LastWriteTime should match.");
            Console.WriteLine("\nTimestamps are transferred.");

            #endregion Preserve Timestamps
         }
         finally
         {
            if (Directory.Exists(tempPath))
            {
               Directory.Delete(tempPath, true, true);
               Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed.");
            }
            Console.WriteLine();
         }
      }
Пример #33
0
        /// <summary>
        /// Makes a recursive snapshot of the directory as it is.
        /// </summary>
        /// <param name="baseDirectory">The directory to start in.</param>
        /// <returns>A file system snapshot</returns>
        public static SnapshotFilesystem MakeFsSnapshot(System.IO.DirectoryInfo baseDirectory)
        {
            DirectoryInfo baseDir = new DirectoryInfo(baseDirectory.FullName);

            if (!baseDir.Exists)
                throw new ArgumentException("Base directory doesn't exist");

            SnapshotFilesystem res = new SnapshotFilesystem();

            if (!baseDir.FullName.EndsWith(Path.DirectorySeparatorChar) && !baseDir.FullName.EndsWith(Path.AltDirectorySeparatorChar))
            {
                // Add ending slash to get a uniform output
                baseDir = new DirectoryInfo(baseDir.FullName + Path.DirectorySeparatorChar);
            }

            res.BasePath = baseDir.FullName;
            res.Items = new LinkedList<SnapshotFilesystemItem>();

            // Make VSS
            // Sequence of calls: http://us.generation-nt.com/answer/volume-shadow-copy-backupcomplete-vss-e-bad-state-help-29094302.html
            IVssImplementation vssImplementation = VssUtils.LoadImplementation();
            IVssBackupComponents backupComponents = vssImplementation.CreateVssBackupComponents();

            backupComponents.InitializeForBackup(null);
            backupComponents.SetContext(VssSnapshotContext.Backup);

            backupComponents.SetBackupState(false, false, VssBackupType.Copy, false);
            backupComponents.GatherWriterMetadata();

            try
            {
                Guid snapshotSetGuid = backupComponents.StartSnapshotSet();
                Guid backupVolumeGuid = backupComponents.AddToSnapshotSet(baseDir.Root.FullName);

                backupComponents.PrepareForBackup();
                backupComponents.DoSnapshotSet();

                VssSnapshotProperties properties = backupComponents.GetSnapshotProperties(backupVolumeGuid);

                DirectoryInfo shadowCopyBase = new DirectoryInfo(Path.Combine(properties.SnapshotDeviceObject, Path.GetDirectoryNameWithoutRoot(baseDir.FullName)));

                if (!shadowCopyBase.FullName.EndsWith(Path.DirectorySeparatorChar) && !shadowCopyBase.FullName.EndsWith(Path.AltDirectorySeparatorChar))
                {
                    // Add ending slash to get a uniform output
                    shadowCopyBase = new DirectoryInfo(shadowCopyBase.FullName + Path.DirectorySeparatorChar);
                }

                // Do stuff
                DoFsSnapshot(shadowCopyBase, shadowCopyBase, res.Items);

                // Delete snapshot
                backupComponents.BackupComplete();
                backupComponents.DeleteSnapshotSet(snapshotSetGuid, false);
            }
            catch (Exception)
            {
                backupComponents.AbortBackup();
            }

            //DoFsSnapshot(baseDirectory, baseDirectory, res.Items);

            return res;
        }
Пример #34
0
 public void Test_AlphaFS___AnalyzeSecurity_LocalAcessShouldNotExist()
 {
    string testDir = GetTempDirectoryName();
    SetSecuritySystem(testDir);
    var dirsec = new DirectoryInfo(testDir + @"\inherited").GetAccessControl();
    AuthorizationRuleCollection accessRules = dirsec.GetAccessRules(true, true, targetType: typeof(SecurityIdentifier));
    Assert.IsFalse(HasLocalAces(accessRules), "local access rules found");
 }
Пример #35
0
 public static FileInfo FileInFolder(DirectoryInfo di, string fn)
 {
     return(FileInFolder(di.FullName, fn));
 }
Пример #36
0
        /// <summary>
        /// Internal method to recursively iterate the file system.
        /// It will fill out the results parameter with items as it finds them.
        /// </summary>
        /// <param name="baseDirectory">Base directory is used to make relative paths. It should always end with a '\' (slash) to generate a uniform and valid output.</param>
        /// <param name="currentDirectory">The directory to iterate.</param>
        /// <param name="results">The results LinkedList to fill out.</param>
        private static void DoFsSnapshot(DirectoryInfo baseDirectory, DirectoryInfo currentDirectory, LinkedList<SnapshotFilesystemItem> results)
        {
            // Self
            SnapshotDirectoryInfo current = new SnapshotDirectoryInfo();
            current.RelativePath = currentDirectory.FullName.Substring(baseDirectory.FullName.Length);

            try
            {
                current.LastAccess = currentDirectory.LastAccessTimeUtc;
                current.LastModified = currentDirectory.LastWriteTimeUtc;
                current.Attributes = (System.IO.FileAttributes)currentDirectory.Attributes;

                current.WasReadable = true;
            }
            catch (System.IO.IOException)
            {
                // Couldn't read details
                current.WasReadable = false;
            }

            // Subfiles
            try
            {
                FileInfo[] files = currentDirectory.GetFiles();

                foreach (FileInfo fileInfo in files)
                {
                    // Single file
                    SnapshotFileInfo file = new SnapshotFileInfo();
                    file.RelativePath = fileInfo.FullName.Substring(baseDirectory.FullName.Length);

                    try
                    {
                        file.LastAccess = fileInfo.LastAccessTimeUtc;
                        file.LastModified = fileInfo.LastWriteTimeUtc;
                        file.Attributes = (System.IO.FileAttributes)fileInfo.Attributes;

                        // Make hash
                        using (System.IO.FileStream fileStream = fileInfo.OpenRead())
                        {
                            byte[] hash = _md5.ComputeHash(fileStream);
                            file.Hash = BitConverter.ToString(hash).Replace("-", "");
                        }

                        file.WasReadable = true;
                    }
                    catch (Exception)
                    {
                        // Couldn't read details
                        file.WasReadable = false;
                    }

                    results.AddLast(file);
                }
            }
            catch (System.IO.IOException)
            {
                // Couldn't read files
                current.WasReadable = false;
            }
            catch (UnauthorizedAccessException)
            {
                // Couldn't read files
                current.WasReadable = false;
            }

            // Subdirs
            try
            {
                DirectoryInfo[] directories = currentDirectory.GetDirectories();

                foreach (DirectoryInfo directoryInfo in directories)
                {
                    DoFsSnapshot(baseDirectory, directoryInfo, results);
                }
            }
            catch (System.IO.IOException)
            {
                // Couldn't read directories
                current.WasReadable = false;
            }
            catch (UnauthorizedAccessException)
            {
                // Couldn't read files
                current.WasReadable = false;
            }

            results.AddLast(current);
        }
Пример #37
0
      private static void SetSecurityAlpha(string directory)
      {
         //create the test structure
         if (Directory.Exists(directory))
            Directory.Delete(directory, true);

         Directory.CreateDirectory(directory);
         Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited"));
         DirectoryInfo testDirInfo = new DirectoryInfo(directory);
         //System.IO.Directory.CreateDirectory(_testDir);
         //System.IO.Directory.CreateDirectory(System.IO.Path.Combine(_testDir, "inherited"));
         //System.IO.DirectoryInfo testDirInfo = new System.IO.DirectoryInfo(_testDir);

         var ds = testDirInfo.GetAccessControl(AccessControlSections.Access);
         ds.SetAccessRuleProtection(true, false);
         ds.AddAccessRule(new FileSystemAccessRule(
               identity: new SecurityIdentifier(WellKnownSidType.WorldSid, null),
               fileSystemRights: FileSystemRights.FullControl,
               inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
               propagationFlags: PropagationFlags.None,
               type: AccessControlType.Allow
               ));

         //using (new PrivilegeEnabler(Privilege.Impersonate, Privilege.Backup, Privilege.Restore, Privilege.Security, Privilege.TakeOwnership, Privilege.TrustedCredManAccess, Privilege.Audit))
         {
            testDirInfo.SetAccessControl(ds);

         }
      }
Пример #38
0
      private void DumpCopy(bool isLocal)
      {
         #region Setup

         Console.WriteLine("\n=== TEST {0} ===", isLocal ? Local : Network);
         string tempPath = Path.GetTempPath("Directory.Copy()-") + Path.GetRandomFileName();
         if (!isLocal) tempPath = Path.LocalToUnc(tempPath);

         string tempPathSource = Path.Combine(tempPath, "Source");
         string tempPathDestination = Path.Combine(tempPath, "Destination");

         bool exception;
         int expectedLastError;
         string expectedException;
         string report;

         string letter = DriveInfo.GetFreeDriveLetter() + @":\";
         if (!isLocal) letter = Path.LocalToUnc(letter);

         string random = Path.GetRandomFileName();
         string fileSource = @"file-source-" + random + ".exe";
         string fileDestination = @"file-destination-" + random + ".exe";

         string folderSource = @"folder-source-" + random;
         string folderDestination = @"folder-destination-" + random;

         string fullPathSource = Path.Combine(tempPath, folderSource, fileSource);
         string fullPathDestinationParent = Path.Combine(tempPath, folderDestination);
         string fullPathDestination = Path.Combine(fullPathDestinationParent, fileDestination);
         if (!isLocal) fullPathSource = Path.LocalToUnc(fullPathSource);
         if (!isLocal) fullPathDestination = Path.LocalToUnc(fullPathDestination);

         DirectoryInfo dirInfoParent = new DirectoryInfo(fullPathDestinationParent);

         #endregion // Setup

         try
         {
            #region UnauthorizedAccessException

            DirectoryInfo dirInfo = Directory.CreateDirectory(fullPathSource);
            Directory.CreateDirectory(fullPathDestinationParent);

            DirectorySecurity dirSecurity;

            string user = (Environment.UserDomainName + @"\" + Environment.UserName).TrimStart('\\');

            // ╔═════════════╦═════════════╦═══════════════════════════════╦════════════════════════╦══════════════════╦═══════════════════════╦═════════════╦═════════════╗
            // ║             ║ folder only ║ folder, sub-folders and files ║ folder and sub-folders ║ folder and files ║ sub-folders and files ║ sub-folders ║    files    ║
            // ╠═════════════╬═════════════╬═══════════════════════════════╬════════════════════════╬══════════════════╬═══════════════════════╬═════════════╬═════════════╣
            // ║ Propagation ║ none        ║ none                          ║ none                   ║ none             ║ InheritOnly           ║ InheritOnly ║ InheritOnly ║
            // ║ Inheritance ║ none        ║ Container|Object              ║ Container              ║ Object           ║ Container|Object      ║ Container   ║ Object      ║
            // ╚═════════════╩═════════════╩═══════════════════════════════╩════════════════════════╩══════════════════╩═══════════════════════╩═════════════╩═════════════╝

            var rule = new FileSystemAccessRule(user, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny);


            expectedLastError = (int)Win32Errors.ERROR_ACCESS_DENIED;
            expectedException = "System.UnauthorizedAccessException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: The caller does not have the required permission.", expectedException);

               // Set DENY for current user.
               dirSecurity = dirInfoParent.GetAccessControl();
               dirSecurity.AddAccessRule(rule);
               dirInfoParent.SetAccessControl(dirSecurity);

               dirInfo.MoveTo(fullPathDestination);
            }
            catch (UnauthorizedAccessException ex)
            {
               Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError));

               exception = true;
               Console.WriteLine("\n\t[{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            catch (Exception ex)
            {
               Console.WriteLine("\n\tCaught Unexpected Exception: [{0}]: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));  
            }
            finally
            {
               // Remove DENY for current user.
               dirSecurity = dirInfoParent.GetAccessControl();
               dirSecurity.RemoveAccessRule(rule);
               dirInfoParent.SetAccessControl(dirSecurity, AccessControlSections.Access);

               Directory.Delete(tempPath, true, true);
            }
            Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);

            Console.WriteLine();

            #endregion // UnauthorizedAccessException

            #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 path specified by sourceDirName is invalid (for example, it is on an unmapped drive).", expectedException);
               Directory.Copy(letter + folderSource, letter + folderDestination, CopyOptions.FailIfExists);
            }
            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));
               Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError));

               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 IOException

            expectedLastError = (int)Win32Errors.ERROR_SAME_DRIVE;
            expectedException = "System.IO.IOException";
            exception = false;
            try
            {
               Console.WriteLine("\nCatch: [{0}]: The sourceDirName and destDirName parameters refer to the same file or directory.", expectedException);
               Directory.Move(letter + folderDestination, letter + folderDestination);
            }
            catch (IOException 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();

            #endregion // IOException

            #region Copy

            CreateDirectoriesAndFiles(tempPathSource, 10, true);

            Dictionary<string, long> props = Directory.GetProperties(tempPathSource, DirectoryEnumerationOptions.Recursive);
            long sourceFolder = props["Directory"];
            long sourceFile = props["File"];
            long sourceSize = props["Size"];

            Console.WriteLine("\nCopy from Source Path: [{0}]", tempPathSource);
            Console.WriteLine("\tTotal Directories: [{0}] Files: [{1}] Size: [{2}]", sourceFolder, sourceFile, Utils.UnitSizeToText(sourceSize));

            StopWatcher(true);
            Directory.Copy(tempPathSource, tempPathDestination, CopyOptions.FailIfExists);
            report = Reporter();

            props = Directory.GetProperties(tempPathDestination, DirectoryEnumerationOptions.Recursive);
            long destinationFolder = props["Directory"];
            long destinationFile = props["File"];
            long destinationSize = props["Size"];

            Console.WriteLine("\nCopied to Destination Path: [{0}]", tempPathDestination);
            Console.WriteLine("\tTotal Directories: [{0}] Files: [{1}] Size: [{2}]{3}", destinationFolder, destinationFile, Utils.UnitSizeToText(destinationSize), report);

            #region IOException

            expectedLastError = (int)Win32Errors.ERROR_FILE_EXISTS;
            expectedException = "System.IO.IOException";
            exception = false;
            try
            {
               Console.WriteLine("\n\nCatch: [{0}]: Copy same directory again: destDirName already exists.", expectedException);
               Directory.Copy(tempPathSource, tempPathDestination, CopyOptions.FailIfExists);
            }
            catch (IOException ex)
            {
               var win32Error = new Win32Exception("", ex);
               Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode));
               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();

            #endregion // IOException

            // Overwrite.
            StopWatcher(true);
            Directory.Copy(tempPathSource, tempPathDestination, CopyOptions.None | CopyOptions.NoBuffering);
            report = Reporter();

            Console.WriteLine("\nCopy again with overwrite enabled.\n{0}", report);

            #endregion // Copy
         }
         finally
         {
            if (Directory.Exists(tempPath))
            {
               Directory.Delete(tempPath, true, true);
               Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed.");
            }
            Console.WriteLine();
         }
      }
Пример #39
0
        private static IEnumerable <string> EnumerateFilesExcludeHidden(string path, IList <string> patterns, bool recursive)
        {
            // when checking for hidden directories, enumerate the directories separately from files to check for hidden flag on directories

            DirectoryInfo di = new DirectoryInfo(path);

            // the root of the drive has the hidden attribute set, so don't stop on this hidden directory
            if (di.Attributes.HasFlag(FileAttributes.Hidden) && (di.Root != di))
            {
                yield break;
            }

            var dirOptions = baseDirOptions;

            if (recursive)
            {
                dirOptions |= DirectoryEnumerationOptions.Recursive;
            }


            DirectoryEnumerationFilters dirFilters = new DirectoryEnumerationFilters
            {
                ErrorFilter = (errorCode, errorMessage, pathProcessed) =>
                {
                    logger.Error($"Find file error {errorCode}: {errorMessage} on {pathProcessed}");
                    return(true);
                }
            };

            dirFilters.InclusionFilter = fsei =>
            {
                return(!fsei.IsHidden);
            };


            DirectoryEnumerationFilters fileFilters = new DirectoryEnumerationFilters
            {
                ErrorFilter = (errorCode, errorMessage, pathProcessed) =>
                {
                    logger.Error($"Find file error {errorCode}: {errorMessage} on {pathProcessed}");
                    return(true);
                }
            };


            bool includeAllFiles = patterns.Count == 0 ||
                                   (patterns.Count == 1 && (patterns[0] == "*.*" || patterns[0] == "*"));

            if (includeAllFiles)
            {
                fileFilters.InclusionFilter = fsei =>
                {
                    return(!fsei.IsHidden);
                };
            }
            else
            {
                fileFilters.InclusionFilter = fsei =>
                {
                    if (fsei.IsHidden)
                    {
                        return(false);
                    }

                    foreach (string pattern in patterns)
                    {
                        if (WildcardMatch(fsei.FileName, pattern, true))
                        {
                            return(true);
                        }
                        else if (pattern == "*.doc" && WildcardMatch(fsei.FileName, "*.doc*", true))
                        {
                            return(true);
                        }
                        else if (pattern == "*.xls" && WildcardMatch(fsei.FileName, "*.xls*", true))
                        {
                            return(true);
                        }
                    }
                    return(false);
                };
            }

            IEnumerable <string> directories = new string[] { path };

            if (recursive)
            {
                directories = directories.Concat(Directory.EnumerateDirectories(path, dirOptions, dirFilters, PathFormat.FullPath));
            }

            foreach (var directory in directories)
            {
                IEnumerable <string> matches = Directory.EnumerateFiles(directory, baseFileOptions, fileFilters, PathFormat.FullPath);

                foreach (var file in matches)
                {
                    yield return(file);
                }
            }
        }
Пример #40
0
      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();
      }
Пример #41
0
 public DirectoryLocalArticle(string path)
     : base()
 {
     Info = new DirectoryInfo(path);
 }