Example #1
0
        private FileSystemMetadata GetDirectoryBDMV(
            string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            FileSystemMetadata dir = _fileSystem.GetDirectoryInfo(path);

            while (dir != null)
            {
                if (string.Equals(dir.Name, "BDMV", StringComparison.OrdinalIgnoreCase))
                {
                    return(dir);
                }
                var parentFolder = _fileSystem.GetDirectoryName(dir.FullName);
                if (string.IsNullOrEmpty(parentFolder))
                {
                    dir = null;
                }
                else
                {
                    dir = _fileSystem.GetDirectoryInfo(parentFolder);
                }
            }

            return(GetDirectory("BDMV", _fileSystem.GetDirectoryInfo(path), 0));
        }
        public static IDirectoryInfo Delete(IFileSystem fileSystem, string path) {
            var di = Substitute.For<IDirectoryInfo>();
            di.FullName.Returns(path);
            di.Exists.Returns(false);
            di.Parent.Returns((IDirectoryInfo)null);
            di.EnumerateFileSystemInfos().ThrowsForAnyArgs<DirectoryNotFoundException>();

            fileSystem.GetDirectoryInfo(path).Returns(di);
            fileSystem.DirectoryExists(path).Returns(false);

            fileSystem.GetDirectoryInfo(path + Path.DirectorySeparatorChar).Returns(di);
            fileSystem.DirectoryExists(path + Path.DirectorySeparatorChar).Returns(false);

            return di;
        }
        public static IDirectoryInfo Create(IFileSystem fileSystem, string path) {
            var di = Substitute.For<IDirectoryInfo>();
            di.FullName.Returns(path);
            di.Exists.Returns(true);
            di.Parent.Returns((IDirectoryInfo)null);
            di.EnumerateFileSystemInfos().Returns(new List<IFileSystemInfo>());

            fileSystem.GetDirectoryInfo(path).Returns(di);
            fileSystem.DirectoryExists(path).Returns(true);

            fileSystem.GetDirectoryInfo(path + Path.DirectorySeparatorChar).Returns(di);
            fileSystem.DirectoryExists(path + Path.DirectorySeparatorChar).Returns(true);

            return di;
        }
Example #4
0
        private string TryFindRInProgramFiles(string folder, ISupportedRVersionRange supportedVersions)
        {
            string         root        = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
            string         baseRFolder = Path.Combine(root + @"Program Files\", folder);
            List <Version> versions    = new List <Version>();

            try {
                IEnumerable <IFileSystemInfo> directories = _fileSystem.GetDirectoryInfo(baseRFolder)
                                                            .EnumerateFileSystemInfos()
                                                            .Where(x => (x.Attributes & FileAttributes.Directory) != 0);
                foreach (IFileSystemInfo fsi in directories)
                {
                    string  subFolderName = fsi.FullName.Substring(baseRFolder.Length + 1);
                    Version v             = GetRVersionFromFolderName(subFolderName);
                    if (supportedVersions.IsCompatibleVersion(v))
                    {
                        versions.Add(v);
                    }
                }
            } catch (IOException) {
                // Don't do anything if there is no RRO installed
            }

            if (versions.Count > 0)
            {
                versions.Sort();
                Version highest = versions[versions.Count - 1];
                return(Path.Combine(baseRFolder, string.Format(CultureInfo.InvariantCulture, "R-{0}.{1}.{2}", highest.Major, highest.Minor, highest.Build)));
            }

            return(string.Empty);
        }
Example #5
0
        /// <summary>
        /// Gets all the R script files in the current project.
        /// </summary>
        public IEnumerable <string> GetRFilePaths()
        {
            string projectDir = Path.GetDirectoryName(ConfiguredProject.UnconfiguredProject.FullPath);
            var    allFiles   = _fileSystem.GetDirectoryInfo(projectDir).GetAllFiles();

            return(allFiles.Where((file) => file.FullName.EndsWithIgnoreCase(".R")).Select((file) => file.FullName.MakeRelativePath(projectDir)));
        }
            public void Apply()
            {
                if (!_fullPath.StartsWithIgnoreCase(_rootDirectory))
                {
                    DeleteInsteadOfRename();
                    return;
                }

                var newDirectoryInfo = _fileSystem.GetDirectoryInfo(_fullPath);
                var newRelativePath  = PathHelper.EnsureTrailingSlash(PathHelper.MakeRelative(_rootDirectory, _fullPath));

                if (!newDirectoryInfo.Exists || !_fileSystemFilter.IsDirectoryAllowed(newRelativePath, newDirectoryInfo.Attributes))
                {
                    DeleteInsteadOfRename();
                    return;
                }

                var oldRelativePath = PathHelper.MakeRelative(_rootDirectory, _oldFullPath);

                if (_entries.ContainsDirectoryEntry(oldRelativePath))
                {
                    _entries.RenameDirectory(oldRelativePath, newRelativePath, _fileSystem.ToShortRelativePath(_fullPath, _rootDirectory));
                }
                else
                {
                    (new DirectoryCreated(_entries, _rootDirectory, _fileSystem, _fileSystemFilter, _fullPath)).Apply();
                }
            }
        public static FileSystemMetadata GetXmlFileInfo(ItemInfo info, IFileSystem fileSystem)
        {
            var path = info.Path;

            if (string.IsNullOrEmpty(path) || BaseItem.MediaSourceManager.GetPathProtocol(path.AsSpan()) != MediaBrowser.Model.MediaInfo.MediaProtocol.File)
            {
                return(null);
            }

            var fileInfo = fileSystem.GetFileSystemInfo(path);

            var directoryInfo = fileInfo.IsDirectory ? fileInfo : fileSystem.GetDirectoryInfo(fileSystem.GetDirectoryName(path));

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, fileSystem.GetFileNameWithoutExtension(path) + ".xml");

            var file = fileSystem.GetFileInfo(specificFile);

            // In a mixed folder, only {moviename}.xml is supported
            if (info.IsInMixedFolder)
            {
                return(file);
            }

            // If in it's own folder, prefer movie.xml, but allow the specific file as well
            var movieFile = fileSystem.GetFileInfo(Path.Combine(directoryPath, "movie.xml"));

            return(movieFile.Exists ? movieFile : file);
        }
Example #8
0
        public static FileSystemMetadata GetXmlFileInfo(ItemInfo info, IFileSystem fileSystem)
        {
            var fileInfo = fileSystem.GetFileSystemInfo(info.Path);

            var directoryInfo = fileInfo.IsDirectory ? fileInfo : fileSystem.GetDirectoryInfo(fileSystem.GetDirectoryName(info.Path));

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, fileSystem.GetFileNameWithoutExtension(info.Path) + ".xml");

            var file = fileSystem.GetFileInfo(specificFile);

            // In a mixed folder, only {moviename}.xml is supported
            if (info.IsInMixedFolder)
            {
                return(file);
            }

            // If in it's own folder, prefer movie.xml, but allow the specific file as well
            var movieFile = fileSystem.GetFileInfo(Path.Combine(directoryPath, "movie.xml"));

            return(movieFile.Exists ? movieFile : file);

            // var file = Path.Combine(directoryPath, fileSystem.GetFileNameWithoutExtension(info.Path) + ".xml")
            // return directoryService.GetFile(Path.ChangeExtension(info.Path, ".xml"));
        }
Example #9
0
            public void Apply()
            {
                if (!_directoryFullPath.StartsWithIgnoreCase(_rootDirectory))
                {
                    return;
                }

                Queue <string> directories = new Queue <string>();

                directories.Enqueue(_directoryFullPath);

                while (directories.Count > 0)
                {
                    var directoryPath         = directories.Dequeue();
                    var directory             = _fileSystem.GetDirectoryInfo(directoryPath);
                    var relativeDirectoryPath = PathHelper.MakeRelative(_rootDirectory, directoryPath);

                    if (!directory.Exists)
                    {
                        continue;
                    }

                    // We don't want to add root directory
                    if (!string.IsNullOrEmpty(relativeDirectoryPath))
                    {
                        relativeDirectoryPath = PathHelper.EnsureTrailingSlash(relativeDirectoryPath);

                        // We don't add symlinks
                        if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                        {
                            continue;
                        }

                        if (!_fileSystemFilter.IsDirectoryAllowed(relativeDirectoryPath, directory.Attributes))
                        {
                            continue;
                        }

                        _entries.AddDirectory(relativeDirectoryPath);
                    }

                    foreach (var entry in directory.EnumerateFileSystemInfos())
                    {
                        if (entry is IDirectoryInfo)
                        {
                            directories.Enqueue(entry.FullName);
                        }
                        else
                        {
                            var relativeFilePath = PathHelper.MakeRelative(_rootDirectory, entry.FullName);

                            if (_fileSystemFilter.IsFileAllowed(relativeFilePath, entry.Attributes))
                            {
                                _entries.AddFile(relativeFilePath);
                            }
                        }
                    }
                }
            }
        public static IDirectoryInfo Delete(IFileSystem fileSystem, string path)
        {
            var di = Substitute.For <IDirectoryInfo>();

            di.FullName.Returns(path);
            di.Exists.Returns(false);
            di.Parent.Returns((IDirectoryInfo)null);
            di.EnumerateFileSystemInfos().ThrowsForAnyArgs <DirectoryNotFoundException>();

            fileSystem.GetDirectoryInfo(path).Returns(di);
            fileSystem.DirectoryExists(path).Returns(false);

            fileSystem.GetDirectoryInfo(path + Path.DirectorySeparatorChar).Returns(di);
            fileSystem.DirectoryExists(path + Path.DirectorySeparatorChar).Returns(false);

            return(di);
        }
        public static IDirectoryInfo Create(IFileSystem fileSystem, string path)
        {
            var di = Substitute.For <IDirectoryInfo>();

            di.FullName.Returns(path);
            di.Exists.Returns(true);
            di.Parent.Returns((IDirectoryInfo)null);
            di.EnumerateFileSystemInfos().Returns(new List <IFileSystemInfo>());

            fileSystem.GetDirectoryInfo(path).Returns(di);
            fileSystem.DirectoryExists(path).Returns(true);

            fileSystem.GetDirectoryInfo(path + Path.DirectorySeparatorChar).Returns(di);
            fileSystem.DirectoryExists(path + Path.DirectorySeparatorChar).Returns(true);

            return(di);
        }
Example #12
0
        FileSystemMetadata GetInfoJson(string path)
        {
            var fileInfo      = _fileSystem.GetFileSystemInfo(path);
            var directoryInfo = fileInfo.IsDirectory ? fileInfo : _fileSystem.GetDirectoryInfo(Path.GetDirectoryName(path));
            var directoryPath = directoryInfo.FullName;
            var specificFile  = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(path) + ".info.json");
            var file          = _fileSystem.GetFileInfo(specificFile);

            return(file);
        }
            public async Task FileWatcherError_RaiseError()
            {
                _fileSystem.GetDirectoryInfo(@"Z:\abc\").Throws <InvalidOperationException>();
                var errorTask = EventTaskSources.MsBuildFileSystemWatcher.Error.Create(_fileSystemWatcher);

                using (_taskScheduler.Pause()) {
                    _fileWatcher.Error += Raise.Event <ErrorEventHandler>(_fileWatcher, new ErrorEventArgs(new InvalidOperationException()));
                }

                await _taskScheduler;

                errorTask.Status.Should().Be(TaskStatus.RanToCompletion);
            }
        private FileSystemMetadata GetXmlFile(string path, bool isInMixedFolder)
        {
            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            var directoryInfo = fileInfo.IsDirectory ? fileInfo : _fileSystem.GetDirectoryInfo(Path.GetDirectoryName(path));

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(path) + ".xml");

            var file = _fileSystem.GetFileInfo(specificFile);

            return(file.Exists ? file : _fileSystem.GetFileInfo(Path.Combine(directoryPath, ComicRackMetaFile)));
        }
Example #15
0
        int GetPathAttribute(string path)
        {
            var di = _file.GetDirectoryInfo(path);

            if (di.Exists)
            {
                return(file_attribute_directory);
            }

            var fi = _file.GetFileInfo(path);

            if (fi.Exists)
            {
                return(file_attribute_normal);
            }

            throw new FileNotFoundException();
        }
Example #16
0
 public static IEnumerable <DiscFileInfo> GetFilesFromPath(this IFileSystem system, string path)
 {
     if (system.FileExists(path))
     {
         yield return(system.GetFileInfo(path));
     }
     else if (system.DirectoryExists(path))
     {
         foreach (var fileInfo in system.GetDirectoryInfo(path).GetFiles())
         {
             yield return(fileInfo);
         }
     }
     else
     {
         Console.WriteLine($"File or folder '{path}' does not exist.");
     }
 }
        private IRInterpreterInfo TryFindRInProgramFiles()
        {
            // Force 64-bit PF
            var programFiles = Environment.GetEnvironmentVariable("ProgramW6432");
            var baseRFolder  = Path.Combine(programFiles, @"R");
            var versions     = new List <Version>();

            try {
                if (_fileSystem.DirectoryExists(baseRFolder))
                {
                    var directories = _fileSystem
                                      .GetDirectoryInfo(baseRFolder)
                                      .EnumerateFileSystemInfos()
                                      .Where(x => (x.Attributes & FileAttributes.Directory) != 0);

                    foreach (IFileSystemInfo fsi in directories)
                    {
                        string subFolderName = fsi.FullName.Substring(baseRFolder.Length + 1);
                        var    v             = GetRVersionFromFolderName(subFolderName);
                        if (SupportedVersions.IsCompatibleVersion(v))
                        {
                            versions.Add(v);
                        }
                    }
                }
            } catch (IOException) {
                // Don't do anything if there is no RRO installed
            }

            if (versions.Count > 0)
            {
                versions.Sort();
                var highest = versions[versions.Count - 1];
                var name    = string.Format(CultureInfo.InvariantCulture, "R-{0}.{1}.{2}", highest.Major, highest.Minor, highest.Build);
                var path    = Path.Combine(baseRFolder, name);
                var ri      = CreateInfo(name, path);
                if (ri.VerifyInstallation(SupportedVersions))
                {
                    return(ri);
                }
            }

            return(null);
        }
Example #18
0
        public PathWalker(List <FileSystemMetadata> del_paths, IFileSystem fs)
        {
            _fs          = fs;
            delete_paths = del_paths;

            foreach (var del_item in del_paths)
            {
                if (del_item.IsDirectory)
                {
                    FileSystemMetadata fsm = fs.GetDirectoryInfo(del_item.FullName);
                    WalkPath(fsm);
                }
                else
                {
                    FileSystemMetadata fsm = fs.GetFileInfo(del_item.FullName);
                    file_full_list.Add(fsm);
                }
            }
        }
        private FileSystemMetadata GetXmlFile(string path)
        {
            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            var directoryInfo = fileInfo.IsDirectory ? fileInfo : _fileSystem.GetDirectoryInfo(Path.GetDirectoryName(path));

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(path) + ".opf");

            var file = _fileSystem.GetFileInfo(specificFile);

            if (file.Exists)
            {
                return(file);
            }

            file = _fileSystem.GetFileInfo(Path.Combine(directoryPath, StandardOpfFile));

            return(file.Exists ? file : _fileSystem.GetFileInfo(Path.Combine(directoryPath, CalibreOpfFile)));
        }
Example #20
0
        /// <summary>
        /// Safely enumerates all files under a given root. If a subdirectory is
        /// inaccessible, its files will not be returned (compare and contrast
        /// with Directory.GetFiles, which will crash without returning any
        /// files at all).
        /// </summary>
        /// <param name="fileSystem">
        /// File system.
        /// </param>
        /// <param name="root">
        /// Directory to enumerate.
        /// </param>
        /// <param name="pattern">
        /// File pattern to return. You may use wildcards * and ?.
        /// </param>
        /// <param name="recurse">
        /// <c>true</c> to return files within subdirectories.
        /// </param>
        public static IEnumerable <IFileInfo> EnumerateFiles(IFileSystem fileSystem, string root, string pattern = "*", bool recurse = true)
        {
            root = EnsureEndSeparator(root);

            var dirs = Enumerable.Repeat(root, 1);

            if (recurse)
            {
                dirs = dirs.Concat(EnumerateDirectories(fileSystem, root, true, false));
            }

            foreach (var dir in dirs)
            {
                var fullDir = Path.IsPathRooted(dir) ? dir : root + dir;
                if (string.IsNullOrEmpty(fullDir))
                {
                    continue;
                }
                IFileInfo[] files = null;
                try {
                    files = fileSystem.GetDirectoryInfo(fullDir)
                            .EnumerateFileSystemInfos(pattern, SearchOption.TopDirectoryOnly)
                            .Where(f => !f.Attributes.HasFlag(FileAttributes.Directory))
                            .OfType <IFileInfo>()
                            .ToArray();
                } catch (UnauthorizedAccessException) {
                } catch (IOException) {
                }

                if (files == null)
                {
                    continue;
                }

                foreach (var f in files)
                {
                    yield return(f);
                }
            }
        }
Example #21
0
        public BDROM(string path, IFileSystem fileSystem)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            _fileSystem = fileSystem;
            //
            // Locate BDMV directories.
            //

            DirectoryBDMV =
                GetDirectoryBDMV(path);

            if (DirectoryBDMV == null)
            {
                throw new Exception("Unable to locate BD structure.");
            }

            DirectoryRoot =
                _fileSystem.GetDirectoryInfo(_fileSystem.GetDirectoryName(DirectoryBDMV.FullName));
            DirectoryBDJO =
                GetDirectory("BDJO", DirectoryBDMV, 0);
            DirectoryCLIPINF =
                GetDirectory("CLIPINF", DirectoryBDMV, 0);
            DirectoryPLAYLIST =
                GetDirectory("PLAYLIST", DirectoryBDMV, 0);
            DirectorySNP =
                GetDirectory("SNP", DirectoryRoot, 0);
            DirectorySTREAM =
                GetDirectory("STREAM", DirectoryBDMV, 0);
            DirectorySSIF =
                GetDirectory("SSIF", DirectorySTREAM, 0);

            if (DirectoryCLIPINF == null ||
                DirectoryPLAYLIST == null)
            {
                throw new Exception("Unable to locate BD structure.");
            }

            //
            // Initialize basic disc properties.
            //

            VolumeLabel = GetVolumeLabel(DirectoryRoot);
            Size        = (ulong)GetDirectorySize(DirectoryRoot);

            if (null != GetDirectory("BDSVM", DirectoryRoot, 0))
            {
                IsBDPlus = true;
            }
            if (null != GetDirectory("SLYVM", DirectoryRoot, 0))
            {
                IsBDPlus = true;
            }
            if (null != GetDirectory("ANYVM", DirectoryRoot, 0))
            {
                IsBDPlus = true;
            }

            if (DirectoryBDJO != null &&
                _fileSystem.GetFilePaths(DirectoryBDJO.FullName).Any())
            {
                IsBDJava = true;
            }

            if (DirectorySNP != null &&
                GetFilePaths(DirectorySNP.FullName, ".mnv").Any())
            {
                IsPSP = true;
            }

            if (DirectorySSIF != null &&
                _fileSystem.GetFilePaths(DirectorySSIF.FullName).Any())
            {
                Is3D = true;
            }

            if (_fileSystem.FileExists(Path.Combine(DirectoryRoot.FullName, "FilmIndex.xml")))
            {
                IsDBOX = true;
            }

            //
            // Initialize file lists.
            //

            if (DirectoryPLAYLIST != null)
            {
                FileSystemMetadata[] files = GetFiles(DirectoryPLAYLIST.FullName, ".mpls").ToArray();
                foreach (var file in files)
                {
                    PlaylistFiles.Add(
                        file.Name.ToUpper(), new TSPlaylistFile(this, file, _fileSystem));
                }
            }

            if (DirectorySTREAM != null)
            {
                FileSystemMetadata[] files = GetFiles(DirectorySTREAM.FullName, ".m2ts").ToArray();
                foreach (var file in files)
                {
                    StreamFiles.Add(
                        file.Name.ToUpper(), new TSStreamFile(file, _fileSystem));
                }
            }

            if (DirectoryCLIPINF != null)
            {
                FileSystemMetadata[] files = GetFiles(DirectoryCLIPINF.FullName, ".clpi").ToArray();
                foreach (var file in files)
                {
                    StreamClipFiles.Add(
                        file.Name.ToUpper(), new TSStreamClipFile(file, _fileSystem));
                }
            }

            if (DirectorySSIF != null)
            {
                FileSystemMetadata[] files = GetFiles(DirectorySSIF.FullName, ".ssif").ToArray();
                foreach (var file in files)
                {
                    InterleavedFiles.Add(
                        file.Name.ToUpper(), new TSInterleavedFile(file));
                }
            }
        }
Example #22
0
        public object Post(SafeDeleteAction request)
        {
            _logger.Info("POST SafeDeleteAction: {0}", request);

            long     item_id = long.Parse(request.item_id);
            BaseItem item    = _lm.GetItemById(item_id);

            List <FileSystemMetadata> del_paths = item.GetDeletePaths(false);
            PathWalker walker = new PathWalker(del_paths, _fs);

            List <KeyValuePair <string, long> > file_list  = walker.GetFileNames();
            Dictionary <string, int>            ext_counts = walker.GetExtCounts();

            // verify action token
            string file_info_string = "";
            string file_list_hash   = "";

            foreach (var file_item in file_list)
            {
                file_info_string += file_item.Key + "|" + file_item.Value + "|";
            }
            using (MD5 md5Hash = MD5.Create())
            {
                byte[]        hashBytes = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(file_info_string));
                StringBuilder sb        = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                file_list_hash = sb.ToString();
            }

            Dictionary <string, object> result = new Dictionary <string, object>();

            if (file_list_hash != request.action_token)
            {
                result.Add("result", false);
                result.Add("message", "The action tokens to not match.");
                return(result);
            }

            // do file move
            string recycle_path = Plugin.Instance.Configuration.RecycledPath;

            if (string.IsNullOrEmpty(recycle_path))
            {
                result.Add("result", false);
                result.Add("message", "Recycle path not set.");
                return(result);
            }

            if (!_fs.DirectoryExists(recycle_path))
            {
                result.Add("result", false);
                result.Add("message", "Recycle path does not exist.");
                return(result);
            }

            // do file moves
            string time_stamp  = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff");
            int    item_number = 0;

            bool   action_result  = true;
            string action_message = "Files moved.";

            foreach (var del_item in del_paths)
            {
                _logger.Info("Item Delete Path: " + del_item.FullName);

                if (del_item.IsDirectory)
                {
                    FileSystemMetadata fsm         = _fs.GetDirectoryInfo(del_item.FullName);
                    string             destination = System.IO.Path.Combine(recycle_path, time_stamp, item_number.ToString());
                    _logger.Info("Item Delete Destination Path: " + destination);

                    try
                    {
                        _fs.CreateDirectory(destination);
                        destination = System.IO.Path.Combine(destination, fsm.Name);
                        _fs.MoveDirectory(del_item.FullName, destination);
                    }
                    catch (Exception e)
                    {
                        action_result  = false;
                        action_message = e.Message;
                    }
                }
                else
                {
                    FileSystemMetadata fsm         = _fs.GetDirectoryInfo(del_item.FullName);
                    string             destination = System.IO.Path.Combine(recycle_path, time_stamp, item_number.ToString());
                    _logger.Info("Item Delete Destination Path: " + destination);

                    try
                    {
                        _fs.CreateDirectory(destination);
                        destination = System.IO.Path.Combine(destination, fsm.Name);
                        _fs.MoveFile(del_item.FullName, destination);
                    }
                    catch (Exception e)
                    {
                        action_result  = false;
                        action_message = e.Message;
                    }
                }

                if (!action_result)
                {
                    break;
                }

                item_number++;
            }

            result.Add("result", action_result);
            result.Add("message", action_message);

            return(result);
        }
Example #23
0
        /// <summary>
        /// Gets the filtered file system entries.
        /// </summary>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="path">The path.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="appHost">The application host.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="args">The args.</param>
        /// <param name="flattenFolderDepth">The flatten folder depth.</param>
        /// <param name="resolveShortcuts">if set to <c>true</c> [resolve shortcuts].</param>
        /// <returns>Dictionary{System.StringFileSystemInfo}.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="path" /> is <c>null</c> or empty.</exception>
        public static FileSystemMetadata[] GetFilteredFileSystemEntries(
            IDirectoryService directoryService,
            string path,
            IFileSystem fileSystem,
            IServerApplicationHost appHost,
            ILogger logger,
            ItemResolveArgs args,
            int flattenFolderDepth = 0,
            bool resolveShortcuts  = true)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var entries = directoryService.GetFileSystemEntries(path);

            if (!resolveShortcuts && flattenFolderDepth == 0)
            {
                return(entries);
            }

            var dict = new Dictionary <string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);

            foreach (var entry in entries)
            {
                var isDirectory = entry.IsDirectory;

                var fullName = entry.FullName;

                if (resolveShortcuts && fileSystem.IsShortcut(fullName))
                {
                    try
                    {
                        var newPath = appHost.ExpandVirtualPath(fileSystem.ResolveShortcut(fullName));

                        if (string.IsNullOrEmpty(newPath))
                        {
                            // invalid shortcut - could be old or target could just be unavailable
                            logger.LogWarning("Encountered invalid shortcut: {Path}", fullName);
                            continue;
                        }

                        // Don't check if it exists here because that could return false for network shares.
                        var data = fileSystem.GetDirectoryInfo(newPath);

                        // add to our physical locations
                        args.AddAdditionalLocation(newPath);

                        dict[newPath] = data;
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "Error resolving shortcut from {Path}", fullName);
                    }
                }
                else if (flattenFolderDepth > 0 && isDirectory)
                {
                    foreach (var child in GetFilteredFileSystemEntries(directoryService, fullName, fileSystem, appHost, logger, args, flattenFolderDepth: flattenFolderDepth - 1, resolveShortcuts: resolveShortcuts))
                    {
                        dict[child.FullName] = child;
                    }
                }
                else
                {
                    dict[fullName] = entry;
                }
            }

            var returnResult = new FileSystemMetadata[dict.Count];
            var index        = 0;
            var values       = dict.Values;

            foreach (var value in values)
            {
                returnResult[index] = value;
                index++;
            }

            return(returnResult);
        }
Example #24
0
        /// <summary>
        /// Gets the filtered file system entries.
        /// </summary>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="path">The path.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="args">The args.</param>
        /// <param name="flattenFolderDepth">The flatten folder depth.</param>
        /// <param name="resolveShortcuts">if set to <c>true</c> [resolve shortcuts].</param>
        /// <returns>Dictionary{System.StringFileSystemInfo}.</returns>
        /// <exception cref="System.ArgumentNullException">path</exception>
        public static Dictionary <string, FileSystemMetadata> GetFilteredFileSystemEntries(IDirectoryService directoryService,
                                                                                           string path,
                                                                                           IFileSystem fileSystem,
                                                                                           ILogger logger,
                                                                                           ItemResolveArgs args,
                                                                                           int flattenFolderDepth = 0,
                                                                                           bool resolveShortcuts  = true)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            if (!resolveShortcuts && flattenFolderDepth == 0)
            {
                return(directoryService.GetFileSystemDictionary(path));
            }

            var entries = directoryService.GetFileSystemEntries(path);

            var dict = new Dictionary <string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);

            foreach (var entry in entries)
            {
                var isDirectory = (entry.Attributes & FileAttributes.Directory) == FileAttributes.Directory;

                var fullName = entry.FullName;

                if (resolveShortcuts && fileSystem.IsShortcut(fullName))
                {
                    var newPath = fileSystem.ResolveShortcut(fullName);

                    if (string.IsNullOrWhiteSpace(newPath))
                    {
                        //invalid shortcut - could be old or target could just be unavailable
                        logger.Warn("Encountered invalid shortcut: " + fullName);
                        continue;
                    }

                    // Don't check if it exists here because that could return false for network shares.
                    var data = fileSystem.GetDirectoryInfo(newPath);

                    // add to our physical locations
                    args.AddAdditionalLocation(newPath);

                    dict[newPath] = data;
                }
                else if (flattenFolderDepth > 0 && isDirectory)
                {
                    foreach (var child in GetFilteredFileSystemEntries(directoryService, fullName, fileSystem, logger, args, flattenFolderDepth: flattenFolderDepth - 1, resolveShortcuts: resolveShortcuts))
                    {
                        dict[child.Key] = child.Value;
                    }
                }
                else
                {
                    dict[fullName] = entry;
                }
            }

            return(dict);
        }
 public IFileInfo GetDirectoryInfo(string sPath)
 {
     return(inner.GetDirectoryInfo(sPath));
 }
Example #26
0
        /// <summary>
        /// Gets the filtered file system entries.
        /// </summary>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="path">The path.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="args">The args.</param>
        /// <param name="flattenFolderDepth">The flatten folder depth.</param>
        /// <param name="resolveShortcuts">if set to <c>true</c> [resolve shortcuts].</param>
        /// <returns>Dictionary{System.StringFileSystemInfo}.</returns>
        /// <exception cref="System.ArgumentNullException">path</exception>
        public static Dictionary<string, FileSystemMetadata> GetFilteredFileSystemEntries(IDirectoryService directoryService,
            string path,
            IFileSystem fileSystem,
            ILogger logger,
            ItemResolveArgs args,
            int flattenFolderDepth = 0,
            bool resolveShortcuts = true)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            if (!resolveShortcuts && flattenFolderDepth == 0)
            {
                return directoryService.GetFileSystemDictionary(path);
            }

            var entries = directoryService.GetFileSystemEntries(path);

            var dict = new Dictionary<string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);

            foreach (var entry in entries)
            {
                var isDirectory = entry.IsDirectory;

                var fullName = entry.FullName;

                if (resolveShortcuts && fileSystem.IsShortcut(fullName))
                {
                    try
                    {
                        var newPath = fileSystem.ResolveShortcut(fullName);

                        if (string.IsNullOrWhiteSpace(newPath))
                        {
                            //invalid shortcut - could be old or target could just be unavailable
                            logger.Warn("Encountered invalid shortcut: " + fullName);
                            continue;
                        }

                        // Don't check if it exists here because that could return false for network shares.
                        var data = fileSystem.GetDirectoryInfo(newPath);

                        // add to our physical locations
                        args.AddAdditionalLocation(newPath);

                        dict[newPath] = data;
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorException("Error resolving shortcut from {0}", ex, fullName);
                    }
                }
                else if (flattenFolderDepth > 0 && isDirectory)
                {
                    foreach (var child in GetFilteredFileSystemEntries(directoryService, fullName, fileSystem, logger, args, flattenFolderDepth: flattenFolderDepth - 1, resolveShortcuts: resolveShortcuts))
                    {
                        dict[child.Key] = child.Value;
                    }
                }
                else
                {
                    dict[fullName] = entry;
                }
            }

            return dict;
        }
Example #27
0
 /// <summary>
 /// Returns full paths of files within a directory
 /// </summary>
 public static IEnumerable <string> GetFiles(this IFileSystem fs, string directory)
 => fs.GetDirectoryInfo(directory).EnumerateFileSystemInfos()
 .Where(fsi => (fsi.Attributes & (FileAttributes.Directory | FileAttributes.Device)) == 0)
 .Select(f => f.FullName);
Example #28
0
 public BdInfoDirectoryInfo(IFileSystem fileSystem, string path)
 {
     _fileSystem = fileSystem;
     _impl       = _fileSystem.GetDirectoryInfo(path);
 }