EnumerateFileSystemInfos() public méthode

public EnumerateFileSystemInfos ( ) : IEnumerable
Résultat IEnumerable
        internal override IEnumerable<FileSystemEntry> ImplFindFiles(String Path)
        {
            String CachedRealPath = RealPath(Path);

            DirectoryInfo DirectoryInfo = new DirectoryInfo(CachedRealPath);

            foreach (var Item in DirectoryInfo.EnumerateFileSystemInfos())
            {
                if (!Item.FullName.StartsWith(CachedRealPath))
                {
                    throw(new Exception("Unexpected FullName"));
                }

                if (Item.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    continue;
                }

                var FileSystemEntry = new LocalFileSystemEntry(this, Path + "/" + Item.Name, Item);

                //FileSystemEntry.Size = File.get
                //Item.Attributes == FileAttributes.
                //

                //FileSystemEntry.Time = Item.
                yield return FileSystemEntry;
            }
        }
        protected override Task<HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfo info, string localFilePath)
        {
            HttpResponseMessage response = Request.CreateResponse();
            using (var zip = new ZipFile())
            {
                foreach (FileSystemInfo fileSysInfo in info.EnumerateFileSystemInfos())
                {
                    bool isDirectory = (fileSysInfo.Attributes & FileAttributes.Directory) != 0;

                    if (isDirectory)
                    {
                        zip.AddDirectory(fileSysInfo.FullName, fileSysInfo.Name);
                    }
                    else
                    {
                        // Add it at the root of the zip
                        zip.AddFile(fileSysInfo.FullName, "/");
                    }
                }

                using (var ms = new MemoryStream())
                {
                    zip.Save(ms);
                    response.Content = ms.AsContent();
                }
            }

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            // Name the zip after the folder. e.g. "c:\foo\bar\" --> "bar"
            response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip";
            return Task.FromResult(response);
        }
        private bool TestCoreCLRIssue()
        {
            string root = null;
            try
            {
                root = Path.GetTempFileName();
                File.Delete(root);
                Directory.CreateDirectory(root);

                var testDir = new DirectoryInfo(root);
                var betaDir = Path.Combine(root, "beta");

                Directory.CreateDirectory(betaDir);

                var beta = testDir.EnumerateFileSystemInfos("beta", SearchOption.TopDirectoryOnly).First() as DirectoryInfo;
                return !beta.Exists;
            }
            finally
            {
                if (root != null && Directory.Exists(root))
                {
                    Directory.Delete(root, true);
                }
            }
        }
		public static void AddDirectory(this ZipArchive archive, string sourceDir)
		{
			DirectoryInfo directoryInfo = new DirectoryInfo(sourceDir);
			sourceDir = directoryInfo.FullName;

			foreach (FileSystemInfo entry in directoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
			{
				string relativePath = entry.FullName.Substring(sourceDir.Length, entry.FullName.Length - sourceDir.Length);
				relativePath = relativePath.TrimStart(new char[]
				{
					Path.DirectorySeparatorChar,
					Path.AltDirectorySeparatorChar
				});

				if (entry is FileInfo)
				{
					archive.AddFile(entry.FullName, relativePath);
				}
				else
				{
					DirectoryInfo subDirInfo = entry as DirectoryInfo;
					if (subDirInfo != null && !subDirInfo.EnumerateFileSystemInfos().Any())
					{
						archive.CreateEntry(relativePath + Path.DirectorySeparatorChar);
					}
				}
			}
		}
        public INode GetTree(string rootPath)
        {
            var directoryInfo = new DirectoryInfo(rootPath);
            if (directoryInfo.Attributes != FileAttributes.Directory)
            {
                var file = new FileInfo(rootPath);
                return new Node
                {
                    Id = file.FullName,
                    Name = file.Name,
                    NodeType = NodeType.File,
                    Children = new INode[0],
                };
            }

            var result = new Node
            {
                Id = directoryInfo.FullName,
                Name = directoryInfo.Name,
                NodeType = NodeType.Folder
            };

            result.Children = directoryInfo.EnumerateFileSystemInfos().Select(fileSystemInfo => new Node { Id = fileSystemInfo.FullName, Name = fileSystemInfo.Name, Children = new INode[0] }).ToList();

            return result;
        }
 public static bool MightContainSolution(this ISimpleRepositoryModel repository)
 {
     var dir = new DirectoryInfo(repository.LocalPath);
     return dir.EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly)
               .Any(x => ((x.Attributes.HasFlag(FileAttributes.Directory) || x.Attributes.HasFlag(FileAttributes.Normal)) &&
                         !x.Name.StartsWith(".", StringComparison.Ordinal) && !x.Name.StartsWith("readme", StringComparison.OrdinalIgnoreCase)));
 }
        protected override Task<HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfo info, string localFilePath)
        {
            HttpResponseMessage response = Request.CreateResponse();
            using (var ms = new MemoryStream())
            {
                using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true))
                {
                    foreach (FileSystemInfo fileSysInfo in info.EnumerateFileSystemInfos())
                    {
                        DirectoryInfo directoryInfo = fileSysInfo as DirectoryInfo;
                        if (directoryInfo != null)
                        {
                            zip.AddDirectory(new DirectoryInfoWrapper(directoryInfo), fileSysInfo.Name);
                        }
                        else
                        {
                            // Add it at the root of the zip
                            zip.AddFile(fileSysInfo.FullName, String.Empty);
                        }
                    }
                }
                response.Content = ms.AsContent();
            }

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            // Name the zip after the folder. e.g. "c:\foo\bar\" --> "bar"
            response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip";
            return Task.FromResult(response);
        }
Exemple #8
0
        public static void ZipDirectory(string dir)
        {
            string zipfile_name = dir + ".zip";
            if (File.Exists(zipfile_name))
            {
                return;
            }

            using (var zip = new ZipFile(Encoding.GetEncoding("shift_jis")))
            {
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;

                var di = new DirectoryInfo(dir);

                foreach (var i in di.EnumerateFileSystemInfos())
                {
                    if (FileAttributes.Directory == (i.Attributes & FileAttributes.Directory))
                    {
                        zip.AddDirectory(i.FullName, i.Name);
                    }
                    else if (FileAttributes.Hidden != (i.Attributes & FileAttributes.Hidden))
                    {
                        zip.AddFile(i.FullName, "");
                    }
                }

                zip.Save(zipfile_name);
            }
        }
 private bool CleanDirectoryPath(CmdletProgress bar, DateTime dtNow, TimeSpan age, DirectoryInfo currentDirecotry, string relativePath)
 {
     var empty = true;
     foreach (var fsi in currentDirecotry.EnumerateFileSystemInfos())
     {
         var currentRelativePath = Path.Combine(relativePath, fsi.Name);
         var di = fsi as DirectoryInfo;
         var fi = fsi as FileInfo;
         if (di != null)
         {
             if (CleanDirectoryPath(bar, dtNow, age, di, currentRelativePath))
             {
                 directoriesDeleted++;
                 empty = DeleteSafe(bar, di.Delete, currentRelativePath);
             }
             else
                 empty = false;
         }
         else if (fi != null)
         {
             if (IsOutAged(dtNow, fi.LastAccessTime, age) || IsOutAged(dtNow, fi.LastWriteTime, age) || IsOutAged(dtNow, fi.LastAccessTime, age))
             {
                 bytesDeleted += fi.Length;
                 filesDeleted++;
                 if (!DeleteSafe(bar, fi.Delete, currentRelativePath))
                     empty = false;
             }
             else
                 empty = false;
         }
     }
     return empty;
 }
Exemple #10
0
        public static AsmAdjancyGraph GetDpxAdjGraph(string binDir)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(binDir) || !Directory.Exists(binDir))
                {
                    var asmAdjGraph = new AsmAdjancyGraph
                    {
                        Msg = $"The bin directory {binDir} is null or does not exist.",
                        St = MetadataTokenStatus.Error
                    };
                    return asmAdjGraph;
                }

                //get all the dll files in the dir
                var di = new DirectoryInfo(binDir);
                var dllsFullNames =
                    di.EnumerateFileSystemInfos("*.dll", SearchOption.TopDirectoryOnly).Select(x => x.FullName).ToArray();

                if (!dllsFullNames.Any())
                {
                    var asmAdjGraph = new AsmAdjancyGraph
                    {
                        Msg = $"The directory {binDir} does not contain any files with a .dll extension.",
                        St = MetadataTokenStatus.Error
                    };
                    return asmAdjGraph;
                }

                //get all the assembly names of direct files and each of thier ref's
                var asmIndxBuffer = new List<Tuple<RankedMetadataTokenAsm, RankedMetadataTokenAsm[]>>();
                foreach (var dll in dllsFullNames)
                {
                    var asmName = AssemblyName.GetAssemblyName(dll);
                    if (asmName == null)
                        continue;
                    var asm = Asm.NfLoadFrom(dll);
                    var refs = asm.GetReferencedAssemblies().ToArray();
                    var mdta = new RankedMetadataTokenAsm
                    {
                        AssemblyName = asm.GetName().FullName,
                        IndexId = -1,
                        DllFullName = dll,
                        HasPdb = File.Exists(Path.ChangeExtension(dll, "pdb"))
                    };
                    asmIndxBuffer.Add(new Tuple<RankedMetadataTokenAsm, RankedMetadataTokenAsm[]>(mdta,
                        refs.Select(x => new RankedMetadataTokenAsm { AssemblyName = x.FullName, IndexId = -2}).ToArray()));
                }
                return GetDpxAdjGraph(asmIndxBuffer);

            }
            catch (Exception ex)
            {
                return new AsmAdjancyGraph {Msg = ex.Message, St = MetadataTokenStatus.Error};
            }
        }
 void ScanDirectory(string directory)
 {
     DirectoryInfo directoryInfo = new DirectoryInfo (directory);
     foreach (FileSystemInfo info in directoryInfo.EnumerateFileSystemInfos ()) {
         queue.Enqueue (info);
         if ((info.Attributes & FileAttributes.Directory) != 0) {
             ScanDirectory (info.FullName);
         }
     }
     queue.Enqueue (null);
 }
        private static void Run_DirectoryInfo_Enumerate() {
            System.Console.Write(" -- Run_DirectoryInfo_Enumerate ");

            var stopwatch = Stopwatch.StartNew();
            var baseDir = new DirectoryInfo(_baseDir);
            var entries = baseDir.EnumerateFileSystemInfos("*", SearchOption.AllDirectories);
            var count = entries.Count();
            stopwatch.Stop();

            System.Console.Write(" -- Count: {0} -- Time {1} = {2}/sec", count, stopwatch.Elapsed, 1000.0 * count / stopwatch.ElapsedMilliseconds);
        }
Exemple #13
0
        private void DeleteEmptyFolders(DirectoryInfo directoryInfo)
        {
            foreach (var directory in directoryInfo.EnumerateDirectories())
            {
                DeleteEmptyFolders(directory);
            }

            if (!directoryInfo.EnumerateFileSystemInfos().Any())
            {
                directoryInfo.Delete();
            }
        }
Exemple #14
0
        private static Task CreateFromDirectoryHelper(string sourcePath, string archiveFilePath, IProgress<float> progress, CancellationToken cancelToken)
        {
            sourcePath = Path.GetFullPath(sourcePath);
            archiveFilePath = Path.GetFullPath(archiveFilePath);

            var folderSeparators = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };

            return Task.Run(() =>
            {
                using (var zipArchive = ZipFile.Open(archiveFilePath, ZipArchiveMode.Create, Encoding.UTF8))
                {
                    var directoryInfo = new DirectoryInfo(sourcePath);

                    // this code results in two run-throughs of the source folder, but
                    // because of windows file system caching, the second run-through below,
                    // will be much faster than the first
                    var totalBytes = directoryInfo
                        .EnumerateFiles("*", SearchOption.AllDirectories)
                        .Sum(fi => fi.Length);
                    var currentBytes = 0L;
                    cancelToken.ThrowIfCancellationRequested();
                    foreach (var info in directoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                    {
                        cancelToken.ThrowIfCancellationRequested();

                        int length = info.FullName.Length - sourcePath.Length;
                        var entryName = info.FullName.Substring(sourcePath.Length, length).TrimStart(folderSeparators);
                        if (info is FileInfo)
                        {
                            var sourceInfo = (FileInfo)info;
                            using (var source = sourceInfo.OpenRead())
                            {
                                var entry = zipArchive.CreateEntry(entryName);
                                entry.LastWriteTime = sourceInfo.GetLastWriteTime();
                                using (var destination = entry.Open())
                                {
                                    currentBytes += StreamCopyHelper(source, destination, progress, totalBytes, currentBytes, cancelToken);
                                }
                            }
                        }
                        else if (info is DirectoryInfo)
                        {
                            if (IsFolderEmpty(info.FullName))
                            {
                                // create entry for empty folder
                                zipArchive.CreateEntry(string.Concat(entryName, Path.DirectorySeparatorChar));
                            }
                        }
                    }
                }
            });
        }
        public void Execute(ProjectConfiguration configuration, string selectedProject)
        {
            DirectoryInfo projectDirectory = new DirectoryInfo(configuration.RootPath);
            List<FileSystemInfo> projectFiles = projectDirectory
                .EnumerateFileSystemInfos("*.csproj", SearchOption.AllDirectories)
                .ToList();

            var targetProjects = configuration.ResolveAssemblies(selectedProject);

            if (_checkOnlyDependencies)
            {
                var projectSetup = new ProjectSetup
                {
                    WhenAssemblyKeyFileNotFound = ProjectSetupBehavior.Valid,
                    WhenContainsFileReferences = ProjectSetupBehavior.Valid,
                    WhenContainsProjectReferences = ProjectSetupBehavior.Warn,
                    WhenReferenceNotResolved = ProjectSetupBehavior.Warn,
                    WhenReferenceResolvedInDifferentLocation = ProjectSetupBehavior.Warn,
                    WhenRequiredProjectLinkNotFound = ProjectSetupBehavior.Valid
                };

                var consoleLogger = ConsoleLogger.Default;

                var generator = new SolutionGenerator.Toolkit.SolutionGenerator(consoleLogger);
                var projectLoader = generator.GetProjectLoader(projectSetup, configuration.RootPath);
                var targetProjectFiles = generator.GetTargetProjectFiles(projectLoader, targetProjects);

                ReferenceWalker walker = new ReferenceWalker(consoleLogger);
                var dependencies = walker.WalkReferencesRecursively(
                    projectSetup, projectLoader, targetProjectFiles,
                    new[] {configuration.ThirdPartiesRootPath}, new HashSet<string>());

                projectFiles = new List<FileSystemInfo>();
                foreach (var dependency in dependencies)
                {
                    var project = projectLoader.GetProjectById(dependency);
                    projectFiles.Add(new FileInfo(project.ProjectFileLocation));
                }
            }

            ChangeOutputPath(projectFiles, configuration.RootPath, configuration.BinariesOutputPath, targetProjects);

            ChangeReferences(projectFiles,
                configuration.RootPath,
                configuration.BinariesOutputPath,
                configuration.TargetFrameworkVersion,
                configuration.GetSystemRuntimeReferenceMode,
                configuration.GetSpecificVersionReferenceMode,
                targetProjects);

            ChangeProjectSettings(projectFiles);
        }
Exemple #16
0
 static public int EnumerateFileSystemInfos(IntPtr l)
 {
     try {
         System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l);
         var ret = self.EnumerateFileSystemInfos();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #17
0
 static void Tidy(DirectoryInfo tree)
 {
     foreach (DirectoryInfo di in tree.EnumerateDirectories())
     {
         Tidy(di);
     }
     tree.Refresh();
     if (!tree.EnumerateFileSystemInfos().Any())
     {
         tree.Delete();
     }
     return;
 }
Exemple #18
0
        private static List <Result> DirectorySearch(EnumerationOptions enumerationOption, Query query, string search,
                                                     string searchCriteria, CancellationToken token)
        {
            var results = new List <Result>();

            var path = FilesFolders.ReturnPreviousDirectoryIfIncompleteString(search);

            var folderList = new List <Result>();
            var fileList   = new List <Result>();

            try
            {
                var directoryInfo = new System.IO.DirectoryInfo(path);

                foreach (var fileSystemInfo in directoryInfo.EnumerateFileSystemInfos(searchCriteria, enumerationOption))
                {
                    if (fileSystemInfo is System.IO.DirectoryInfo)
                    {
                        folderList.Add(ResultManager.CreateFolderResult(fileSystemInfo.Name, fileSystemInfo.FullName,
                                                                        fileSystemInfo.FullName, query, true, false));
                    }
                    else
                    {
                        fileList.Add(ResultManager.CreateFileResult(fileSystemInfo.FullName, query, true, false));
                    }

                    token.ThrowIfCancellationRequested();
                }
            }
            catch (Exception e)
            {
                if (!(e is ArgumentException))
                {
                    throw e;
                }

                results.Add(new Result {
                    Title = e.Message, Score = 501
                });

                return(results);

#if DEBUG // Please investigate and handle error from DirectoryInfo search
#else
                Log.Exception($"|Flow.Launcher.Plugin.Explorer.DirectoryInfoSearch|Error from performing DirectoryInfoSearch", e);
#endif
            }

            // Initial ordering, this order can be updated later by UpdateResultView.MainViewModel based on history of user selection.
            return(results.Concat(folderList.OrderBy(x => x.Title)).Concat(fileList.OrderBy(x => x.Title)).ToList());
        }
		public IEnumerable<IFileSystemObject> GetContentsEnumerable(string path)
		{
			DirectoryInfo pathDir = new DirectoryInfo(path);
			if (!pathDir.Exists) { throw new ArgumentException(path + " does not exist"); }

			return pathDir.EnumerateFileSystemInfos()
				.OrderBy(c =>
				{
					if (c.Attributes.HasFlag(FileAttributes.Directory)) { return 0; }
					else if (c.Attributes.HasFlag(FileAttributes.Archive)) { return 1; }
					else { return 2; }
				})
				.Select(c => Create(c));
		}
Exemple #20
0
        private static void CopyDirectory(string source, string destination, bool overwrite, bool copyEmptyDirectories, bool copySubDirectories, ref int count)
        {
            DirectoryInfo sourceDirectory = new DirectoryInfo(source);

            if (!copyEmptyDirectories && !sourceDirectory.EnumerateFileSystemInfos().Any())
                return;

            foreach (FileInfo fileInfo in sourceDirectory.GetFiles())
                CopyFile(fileInfo.FullName, Path.Combine(destination, fileInfo.Name), overwrite, true, ref count);

            if (!copySubDirectories)
                return;

            foreach (DirectoryInfo directoryInfo in sourceDirectory.GetDirectories())
                CopyDirectory(directoryInfo.FullName, Path.Combine(destination, directoryInfo.Name), overwrite, copyEmptyDirectories, copySubDirectories, ref count);
        }
Exemple #21
0
 static public int EnumerateFileSystemInfos__String__SearchOption(IntPtr l)
 {
     try {
         System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l);
         System.String           a1;
         checkType(l, 2, out a1);
         System.IO.SearchOption a2;
         checkEnum(l, 3, out a2);
         var ret = self.EnumerateFileSystemInfos(a1, a2);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 public QueryResult<FolderModel> ReadChildren(GetDataInfo getInfo, string parentKey, int level, string path, bool includeFiles)
 {
     string fullpath = Path.GetFullPath(Path.Combine(ROOT,path));
     DirectoryInfo dinfo = new DirectoryInfo(fullpath);
     if (!includeFiles)
     {
         var dirs = dinfo.EnumerateDirectories();
         var res = dirs.Select(d => new FolderModel { Key = Guid.NewGuid().ToString(), ParentKey = parentKey, HasSubDirs = d.EnumerateDirectories().Any(), Level = level, Name = d.Name, IsFolder = true }).OrderBy(d=>d.Name);
         return new QueryResult<FolderModel>(res);
     }
     else
     {
         var fileSyst = dinfo.EnumerateFileSystemInfos();
         var res2 = fileSyst.Select(d => new FolderModel { Key = Guid.NewGuid().ToString(), ParentKey = parentKey, HasSubDirs = (d is DirectoryInfo) ? ((DirectoryInfo)d).EnumerateFileSystemInfos().Any() : false, Level = level, Name = d.Name, IsFolder = (d is DirectoryInfo) }).OrderByDescending(d=>d.IsFolder).ThenBy(d=>d.Name);
         return new QueryResult<FolderModel>(res2);
     }
 }
Exemple #23
0
        public static void DirectoryInfoTest()
        {
            Console.WriteLine("\n ------------ DIRECTORYINFO CLASS TEST ++++++++++++ ");

            var path  = Directory.GetCurrentDirectory() + "\\DirInfo";
            var path2 = Directory.GetCurrentDirectory() + "\\DirInfo2";

            /*Creation */
            DirectoryInfo di = new System.IO.DirectoryInfo(path);  // via ctrol

            di.Create();
            di.CreateSubdirectory("SubDir");

            var dinfo = Directory.CreateDirectory(path + "\\newDir"); //via Directory.CreateDirectory

            FileAttributes fileAttributes = di.Attributes;            //enum

            Console.WriteLine(fileAttributes.ToString());

            //di.CreateObjRef todo: wtf
            Console.WriteLine("Created: {0}", di.CreationTime.ToShortTimeString());
            //di.Delete();
            //di.EnumerateDirectories();
            var dirs = di.EnumerateDirectories(searchPattern: "*", searchOption: SearchOption.AllDirectories);// IEnumerable<DirInfo>

            Parallel.ForEach(dirs, (dir) => { Console.WriteLine(dir); });

            var files = di.EnumerateFiles(searchPattern: "*.txt");    // IEnumerable<FileInfo>

            Parallel.ForEach(files, (file) => { Console.WriteLine(file); });;

            IEnumerable <FileSystemInfo> filesSystemInfo = di.EnumerateFileSystemInfos(searchPattern: "*");

            Console.WriteLine("Exists: {0} ", di.Exists);
            Console.WriteLine("Extension: {0}", di.Extension);
            Console.WriteLine(di.FullName);
            DirectoryInfo[] dis = di.GetDirectories();
            di.GetFiles(searchOption: SearchOption.AllDirectories, searchPattern: "*.txt");
            // object lts = di.GetLifetimeService(); todo: wtf
            //di.GetObjectData()  wtf
            //di.MoveTo()



            di.InitializeLifetimeService();  //todo
        }
Exemple #24
0
        public ActionResult Files(string id, string path)
        {
            var dir = GetFolder(id).Parent;
            if (path == null) path = "";
            path = path.Replace("/" + id, "\\");
            dir = new DirectoryInfo(dir.FullName + "\\" + path);
            //if (!dir.Exists)
            //    return HttpNotFound("Not found " + dir.FullName);
            var files = dir.EnumerateFileSystemInfos().Select(x => new {
                x.Name,
                IsDirectory = x is DirectoryInfo,
                Size = (x is FileInfo) ? ((FileInfo)x).Length : 0 ,
                LastModified = x.LastWriteTimeUtc
            }).OrderByDescending(x=>x.IsDirectory).ThenBy(x=>x.Name);

            return Json(files, JsonRequestBehavior.AllowGet);
        }
        private static IPropagatorBlock<string, KeyValuePair<string, long>> CreateCustomBlock()
        {
            var directoryBrowserBlock = new TransformManyBlock<string, string>(path =>
            {
                var dir = new DirectoryInfo(path);
                return dir.EnumerateFileSystemInfos()
                    .Select(fi => fi.FullName);
            });
            var fileSizeCalculator = new TransformBlock<string, KeyValuePair<string, long>>(fileName =>
            {
                var fi = new FileInfo(fileName);
                return new KeyValuePair<string, long>(fileName, fi.Length);
            });

            directoryBrowserBlock.LinkTo(fileSizeCalculator, new DataflowLinkOptions { PropagateCompletion = true }, File.Exists);
            var customBlock = DataflowBlock.Encapsulate(directoryBrowserBlock, fileSizeCalculator);
            return customBlock;
        }
Exemple #26
0
 private List<ExtendedFileInfo> GetExtendedFileInfo(DirectoryInfo directoryInfo)
 {
     List<ExtendedFileInfo> filesToProcess = new List<ExtendedFileInfo>();
     if (configuration.TagFolders.Contains(directoryInfo.Name))
     {
         foreach (FileSystemInfo toRename in directoryInfo.EnumerateFileSystemInfos())
         {
             filesToProcess.AddRange(GetExtendedFileInfo(toRename));
         }
     }
     else
     {
         foreach (FileInfo file in directoryInfo.GetFiles("*", SearchOption.AllDirectories))
         {
             filesToProcess.Add(GetExtendedFileInfo(file));
         }
     }
     return filesToProcess;
 }
        public string CompileFromFolder(string folder, out byte[] buffer)
        {
            var dirInfo = new DirectoryInfo(HostingEnvironment.MapPath(folder));
            if (!dirInfo.Exists)
            {
                buffer = new byte[0];
                return "Pasta {0} não encontada".Fmt(folder);
            }

            Dictionary<string, string> source = new Dictionary<string, string>();

            foreach (var file in dirInfo.EnumerateFileSystemInfos("*.cs", SearchOption.AllDirectories))
            {
                var src = File.ReadAllText(file.FullName);
                source.Add(file.Name, src);
            }

            return CompileFromSource(source, out buffer);
        }
Exemple #28
0
 private void sendFolder(string path)
 {
     string head, body, html, pathFromRoot = path.Substring(ServerInstance.WebRoot.Length);
     if (pathFromRoot.Equals("/"))
     {
         pathFromRoot = "";
     }
     head = @"<head><title>" + pathFromRoot + @"</title></head>";
     body = @"<body><lu>";
     DirectoryInfo dirInfo = new DirectoryInfo(path);
     FileSystemInfo[] fileSystemInfos = dirInfo.EnumerateFileSystemInfos().ToArray();
     foreach (FileSystemInfo info in fileSystemInfos)
     {
         body += @"<li><a href='" + pathFromRoot + "/" + info.Name + @"'>" + info.Name + @"</a></li>";
     }
     body += @"</lu></body>";
     html = @"<html>" + head + body + @"</html>";
     sendHTMLString(html, 200, "OK");
 }
Exemple #29
0
        /// <summary>Delete the associated test directory.</summary>
        protected virtual void Dispose(bool disposing)
        {
            try
            {
                try
                {
                    Directory.Delete(TestDirectory, recursive: true);
                }
                catch (UnauthorizedAccessException)
                {
                    DirectoryInfo di = new DirectoryInfo(TestDirectory);
                    foreach (FileSystemInfo fsi in di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                    {
                        fsi.Attributes = FileAttributes.Normal;
                    }

                    Directory.Delete(TestDirectory, recursive: true);
                }
            }
            catch {  } // avoid exceptions escaping Dispose
        }
        public static IEnumerable <FileInfo> EnumerateAllFiles(this DirectoryInfo directory)
        {
            if (directory != null)
            {
                foreach (FileSystemInfo item in directory.EnumerateFileSystemInfos())
                {
                    DirectoryInfo directoryInfo = item as DirectoryInfo;

                    if (directoryInfo != null)
                    {
                        foreach (var fileinfo in directoryInfo.EnumerateAllFiles())
                        {
                            yield return(fileinfo);
                        }
                    }
                    else if (item is FileInfo)
                    {
                        yield return(item as FileInfo);
                    }
                }
            }
        }
Exemple #31
0
        /// <summary>
        ///
        /// </summary>
        private void CheckRemoveOldFiles()
        {
            System.IO.DirectoryInfo       dinfo    = new System.IO.DirectoryInfo(mLogDirector);
            Dictionary <DateTime, string> logFiles = new Dictionary <DateTime, string>();

            if (dinfo.Exists)
            {
                foreach (var vv in dinfo.EnumerateFileSystemInfos())
                {
                    string   sfileName = vv.Name;
                    DateTime dt        = new DateTime(int.Parse(sfileName.Substring(0, 4)), int.Parse(sfileName.Substring(4, 2)), int.Parse(sfileName.Substring(6, 2)), int.Parse(sfileName.Substring(8, 2)), int.Parse(sfileName.Substring(10, 2)), int.Parse(sfileName.Substring(12, 2)));
                    if (!logFiles.ContainsKey(dt))
                    {
                        logFiles.Add(dt, vv.FullName);
                    }
                }
            }


            if (logFiles.Count > 6)
            {
                foreach (var vv in logFiles.OrderBy(e => e.Key).Take(5))
                {
                    if (System.IO.File.Exists(vv.Value))
                    {
                        try
                        {
                            if (System.IO.File.GetAttributes(vv.Value) != FileAttributes.ReadOnly)
                            {
                                System.IO.File.Delete(vv.Value);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
        public static void EnumFiles(this DirectoryInfo directory, Func <FileInfo, bool> action)
        {
            if (directory != null)
            {
                foreach (FileSystemInfo item in directory.EnumerateFileSystemInfos())
                {
                    DirectoryInfo directoryInfo = item as DirectoryInfo;

                    if (directoryInfo != null)
                    {
                        directoryInfo.EnumFiles(action);
                    }
                    else
                    {
                        bool?continu = action?.Invoke(item as FileInfo);
                        if (continu != true)
                        {
                            break;
                        }
                    }
                }
            }
        }
Exemple #33
0
 public IEnumerable <IFileSystemInfo> EnumerateFileSystemInfos()
 {
     return(_inner.EnumerateFileSystemInfos().Select(Wrap).WhereNotNull());
 }
        private static void DoGetFileSystemInfos_Delete()
        {
            String chkptFlag = "chkpt_dgim_";
            int failCount = 0;

            s_utils.CreateTestDirs();

            // directoryinfo
            DirectoryInfo di = new DirectoryInfo(s_utils.testDir);
            IEnumerable<FileSystemInfo> fis = di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories);
            HashSet<String> disAsHS = new HashSet<string>();
            int count = 0;

            try
            {
                foreach (FileSystemInfo d in fis)
                {
                    disAsHS.Add(d.FullName);
                    count++;
                    if (count == 2)
                        s_utils.ChangeFSDelete();
                }
                if (!disAsHS.SetEquals(new HashSet<String>(s_utils.expected_Dirs_Changed.Union(s_utils.expected_Files_Changed))))
                {
                    failCount++;
                    Console.WriteLine(chkptFlag + "1: didn't get expected files....");
                    foreach (FileSystemInfo f in fis)
                    {
                        Console.WriteLine(f.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                failCount++;
                Console.WriteLine(chkptFlag + "2: got wrong exception");
                Console.WriteLine(ex);
            }

            String testName = "deleteFilesWhileEnumerating";
            s_utils.PrintTestStatus(testName, "DirectoryInfo.EnumerateFileSystemInfos", failCount);
        }
        private static void TestGetFileSystemInfosFast(String path, String pattern, String testDescription, Exception expectedException)
        {
            int failCount = 0;
            String chkptFlag = "chkpt_spgfse_";
            String methodName = "DirectoryInfo.EnumerateFileSystemInfos";

            try
            {
                DirectoryInfo di = new DirectoryInfo(path);
                IEnumerable<FileSystemInfo> dirs1 = di.EnumerateFileSystemInfos(pattern);

                Console.WriteLine(chkptFlag + "1: didn't throw");
                failCount++;
            }
            catch (Exception e)
            {
                if (e.GetType() != expectedException.GetType())
                {
                    failCount++;
                    Console.WriteLine(chkptFlag + "2: threw wrong exception");
                    Console.WriteLine(e);
                }
            }

            try
            {
                DirectoryInfo di = new DirectoryInfo(path);
                IEnumerable<FileSystemInfo> dirs2 = di.EnumerateFileSystemInfos(pattern, SearchOption.AllDirectories);

                Console.WriteLine(chkptFlag + "3: didn't throw");
                failCount++;
            }
            catch (Exception e)
            {
                if (e.GetType() != expectedException.GetType())
                {
                    failCount++;
                    Console.WriteLine(chkptFlag + "4: threw wrong exception");
                    Console.WriteLine(e);
                }
            }

            s_utils.PrintTestStatus(testDescription, methodName, failCount);
        }
        private static void DoDirectoryInfoGetFileSystemInfosTest(String path, String searchPattern, SearchOption searchOption, HashSet<String> expected)
        {
            String chkptFlag = "chkpt_dgi1_";
            int failCount = 0;

            // directoryinfo
            DirectoryInfo di = new DirectoryInfo(path);
            IEnumerable<FileSystemInfo> fis = di.EnumerateFileSystemInfos(searchPattern, searchOption);
            HashSet<String> disAsHS = new HashSet<string>();
            foreach (FileSystemInfo d in fis)
            {
                disAsHS.Add(d.FullName);
            }

            if (!disAsHS.SetEquals(expected))
            {
                failCount++;
                Console.WriteLine(chkptFlag + "1: didn't get expected files....");
                foreach (FileSystemInfo f in fis)
                {
                    Console.WriteLine(f.Name);
                }
            }

            String testName = String.Format("SP={0}, SO={1}", searchPattern, searchOption);
            s_utils.PrintTestStatus(testName, "DirectoryInfo.EnumerateFileSystemInfos", failCount);
        }
Exemple #37
0
        // From MSDN: http://msdn.microsoft.com/en-us/library/bb762914.aspx
        public static void CopyDirectoryRecursive(string sourceDirPath, string destinationDirPath, bool overwrite = true)
        {
            // Get the subdirectories for the specified directory.
            var sourceDir = new DirectoryInfo(sourceDirPath);

            if (!sourceDir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sourceDirPath);
            }

            // If the destination directory doesn't exist, create it.
            if (!DirectoryExists(destinationDirPath))
            {
                CreateDirectory(destinationDirPath);
            }

            // Get the files in the directory and copy them to the new location.
            foreach (FileSystemInfo sourceFileSystemInfo in sourceDir.EnumerateFileSystemInfos())
            {
                var sourceFile = sourceFileSystemInfo as FileInfo;
                if (sourceFile != null)
                {
                    string destinationFilePath = Path.Combine(destinationDirPath, sourceFile.Name);
                    Instance.File.Copy(sourceFile.FullName, destinationFilePath, overwrite);
                }
                else
                {
                    var sourceSubDir = sourceFileSystemInfo as DirectoryInfo;
                    if (sourceSubDir != null)
                    {
                        // Copy sub-directories and their contents to new location.
                        string destinationSubDirPath = Path.Combine(destinationDirPath, sourceSubDir.Name);
                        CopyDirectoryRecursive(sourceSubDir.FullName, destinationSubDirPath, overwrite);
                    }
                }
            }
        }
Exemple #38
0
        private static void DeleteEmptyFolders(DirectoryInfo di)
        {
            if (!di.Exists)
            {
                return;
            }

            foreach (var d in di.EnumerateDirectories())
            {
                DeleteEmptyFolders(d);
            }

            if (!di.EnumerateFileSystemInfos().Any())
            {
                di.Delete();
            }
        }
Exemple #39
0
        /// <summary>
        /// Enumerates the file system infos.
        /// </summary>
        /// <param name="This">This DirectoryInfo.</param>
        /// <param name="mode">The recursion mode.</param>
        /// <param name="recursionFilter">The filter to use for recursing into sub-directories (Walks on <c>true</c>; otherwise, skips recursion).</param>
        /// <returns>
        /// The FileSystemInfos
        /// </returns>
        /// <exception cref="System.NotSupportedException">RecursionMode</exception>
        public static IEnumerable <FileSystemInfo> EnumerateFileSystemInfos(this DirectoryInfo This, RecursionMode mode, Func <DirectoryInfo, bool> recursionFilter = null)
        {
            switch (mode)
            {
            case RecursionMode.ToplevelOnly: {
#if NET40
                foreach (var result in This.EnumerateFileSystemInfos())
#else
                foreach (var result in This.GetFileSystemInfos())
#endif
                { yield return(result); }

                break;
            }

            case RecursionMode.ShortestPathFirst: {
                var results = new Queue <DirectoryInfo>();
                results.Enqueue(This);
                while (results.Any())
                {
                    var result = results.Dequeue();
#if NET40
                    foreach (var fsi in result.EnumerateFileSystemInfos())
                    {
#else
                    foreach (var fsi in result.GetFileSystemInfos())
                    {
#endif
                        yield return(fsi);

                        var di = fsi as DirectoryInfo;
                        if (di == null)
                        {
                            continue;
                        }

                        if (recursionFilter == null || recursionFilter(di))
                        {
                            results.Enqueue(di);
                        }
                    }
                }
                break;
            }

            case RecursionMode.DeepestPathFirst: {
                var results = new Stack <DirectoryInfo>();
                results.Push(This);
                while (results.Any())
                {
                    var result = results.Pop();
#if NET40
                    foreach (var fsi in result.EnumerateFileSystemInfos())
                    {
#else
                    foreach (var fsi in result.GetFileSystemInfos())
                    {
#endif
                        yield return(fsi);

                        var di = fsi as DirectoryInfo;
                        if (di == null)
                        {
                            continue;
                        }

                        if (recursionFilter == null || recursionFilter(di))
                        {
                            results.Push(di);
                        }
                    }
                }
                break;
            }

            default: {
                throw new NotSupportedException(nameof(RecursionMode));
            }
            }
        }
Exemple #40
0
 public IEnumerable <IFileSystemInfo> EnumerateFileSystemInfos()
 {
     return(inner.EnumerateFileSystemInfos().Select(Wrap));
 }
        /// <summary>
        /// Enumerate a directory at the given path, if any.
        /// </summary>
        /// <param name="subpath">A path under the root directory</param>
        /// <returns>Contents of the directory. Caller must check Exists property.</returns>
        public IDirectoryContents GetDirectoryContents(string subpath)
        {
            try
            {
                if (subpath == null)
                {
                    return new NotFoundDirectoryContents();
                }

                // Relative paths starting with a leading slash okay
                if (subpath.StartsWith("/", StringComparison.Ordinal))
                {
                    subpath = subpath.Substring(1);
                }

                // Absolute paths not permitted.
                if (Path.IsPathRooted(subpath))
                {
                    return new NotFoundDirectoryContents();
                }

                var fullPath = GetFullPath(subpath);
                if (fullPath != null)
                {
                    var directoryInfo = new DirectoryInfo(fullPath);
                    if (!directoryInfo.Exists)
                    {
                        return new NotFoundDirectoryContents();
                    }

                    var physicalInfos = directoryInfo
                        .EnumerateFileSystemInfos()
                        .Where(info => !FileSystemInfoHelper.IsHiddenFile(info));
                    var virtualInfos = new List<IFileInfo>();
                    foreach (var fileSystemInfo in physicalInfos)
                    {
                        var fileInfo = fileSystemInfo as FileInfo;
                        if (fileInfo != null)
                        {
                            virtualInfos.Add(new PhysicalFileInfo(_filesWatcher, fileInfo));
                        }
                        else
                        {
                            virtualInfos.Add(new PhysicalDirectoryInfo((DirectoryInfo)fileSystemInfo));
                        }
                    }

                    return new EnumerableDirectoryContents(virtualInfos);
                }
            }
            catch (DirectoryNotFoundException)
            {
            }
            catch (IOException)
            {
            }
            return new NotFoundDirectoryContents();
        }
Exemple #42
0
 /// <summary>
 /// Returns an enumerable collection of file system information in the current
 /// directory.
 /// </summary>
 /// <returns>
 /// An enumerable collection of file system information in the current directory.
 /// </returns>
 /// <exception cref=" <exception cref="System.IO.DirectoryNotFoundException">">
 /// The path encapsulated in the System.IO.FileSystemInfo object is invalid (for
 /// example, it is on an unmapped drive).
 /// </exception>
 /// <exception cref="System.Security.SecurityException">
 /// The caller does not have the required permission.
 /// </exception>
 public IEnumerable <FileSystemInfo> EnumerateFileSystemInfos()
 {
     return(_directoryInfo.EnumerateFileSystemInfos());
 }