当前位置: 首页>>代码示例>>C#>>正文


C# DirectoryInfo.Where方法代码示例

本文整理汇总了C#中System.IO.DirectoryInfo.Where方法的典型用法代码示例。如果您正苦于以下问题:C# DirectoryInfo.Where方法的具体用法?C# DirectoryInfo.Where怎么用?C# DirectoryInfo.Where使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.DirectoryInfo的用法示例。


在下文中一共展示了DirectoryInfo.Where方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            const string root = @"C:\Users\sp\Source\Repos\ChangeTracking\Source";
            var excluded = new[] { @"\obj", @"\bin", @"\Properties", ".vs", @"\packages" };

            Func<string, bool> isIncluded = (name) => excluded.All(e => !name.Contains(e));

            var path = new DirectoryInfo(root)
                .GetDirectories("*", SearchOption.AllDirectories)
                .Select(di => di.FullName)
                .Where(isIncluded)
                .SelectMany(Directory.GetFiles)
                .ToList();

            XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
            var csproj = path.Where(p => Path.GetExtension(p) == ".csproj");
            var used = csproj
                .Select(XElement.Load)
                .Elements(ns + "ItemGroup")
                .Elements(ns + "Compile")
                .Attributes("Include")
                .Select(a => a.Value)
                .Where(isIncluded)
                .Select(Path.GetFileName);

            var cs = path
                .Where(p => Path.GetExtension(p) == ".cs")
                .Select(Path.GetFileName);

            var unused = cs.Except(used);
            unused.ToList().ForEach(Console.WriteLine);
        }
开发者ID:gammja,项目名称:UFF,代码行数:32,代码来源:Program.cs

示例2: ApplyDeltaPackage

        public ReleasePackage ApplyDeltaPackage(ReleasePackage basePackage, ReleasePackage deltaPackage, string outputFile)
        {
            Contract.Requires(deltaPackage != null);
            Contract.Requires(!String.IsNullOrEmpty(outputFile) && !File.Exists(outputFile));

            string workingPath;
            string deltaPath;

            using (Utility.WithTempDirectory(out deltaPath))
            using (Utility.WithTempDirectory(out workingPath))
            using (var deltaZip = new ZipFile(deltaPackage.InputPackageFile))
            using (var baseZip = new ZipFile(basePackage.InputPackageFile)) {
                deltaZip.ExtractAll(deltaPath);
                baseZip.ExtractAll(workingPath);

                var pathsVisited = new List<string>();

                var deltaPathRelativePaths = new DirectoryInfo(deltaPath).GetAllFilesRecursively()
                    .Select(x => x.FullName.Replace(deltaPath + Path.DirectorySeparatorChar, ""))
                    .ToArray();

                // Apply all of the .diff files
                deltaPathRelativePaths
                    .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                    .ForEach(file => {
                        pathsVisited.Add(Regex.Replace(file, @".diff$", "").ToLowerInvariant());
                        applyDiffToFile(deltaPath, file, workingPath);
                    });

                // Delete all of the files that were in the old package but
                // not in the new one.
                new DirectoryInfo(workingPath).GetAllFilesRecursively()
                    .Select(x => x.FullName.Replace(workingPath + Path.DirectorySeparatorChar, "").ToLowerInvariant())
                    .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase) && !pathsVisited.Contains(x))
                    .ForEach(x => {
                        this.Log().Info("{0} was in old package but not in new one, deleting", x);
                        File.Delete(Path.Combine(workingPath, x));
                    });

                // Update all the files that aren't in 'lib' with the delta
                // package's versions (i.e. the nuspec file, etc etc).
                deltaPathRelativePaths
                    .Where(x => !x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                    .ForEach(x => {
                        this.Log().Info("Updating metadata file: {0}", x);
                        File.Copy(Path.Combine(deltaPath, x), Path.Combine(workingPath, x), true);
                    });

                using (var zf = new ZipFile(outputFile)) {
                    zf.AddDirectory(workingPath);
                    zf.Save();
                }
            }

            return new ReleasePackage(outputFile);
        }
开发者ID:christianlang,项目名称:Shimmer,代码行数:56,代码来源:DeltaPackage.cs

示例3: PreLoadAssembliesFromPath

        public void PreLoadAssembliesFromPath(string p)
        {
            //get all .dll files from the specified path and load the lot
            //you might not want recursion - handy for localised assemblies
            //though especially.
            var assemblyFiles = new DirectoryInfo(p).GetFiles("*.dll", SearchOption.AllDirectories);

            foreach (var assemblyName in assemblyFiles
                .Where(Settings.Filter)
                .Select(fi => fi.FullName)
                .Select(AssemblyName.GetAssemblyName)
                .Where(a => !AppDomain.CurrentDomain
                    .GetAssemblies()
                    .Any(assembly => AssemblyName.ReferenceMatchesDefinition(a, assembly.GetName()))))
            {
                //crucial - USE THE ASSEMBLY NAME.
                //in a web app, this assembly will automatically be bound from the
                //Asp.Net Temporary folder from where the site actually runs.
                try
                {
                    Assembly.Load(assemblyName);
                }
                catch (BadImageFormatException)
                {
                    //Debug.WriteLine(e); // TODO: just ignore this?
                }
            }
        }
开发者ID:net-industry,项目名称:net-tools,代码行数:28,代码来源:AssemblyPreloader.cs

示例4: UpdateNuspecAndAssemblyInfo

		public UpdatePackagesStep UpdateNuspecAndAssemblyInfo()
		{
			var checkPackages =
				new DirectoryInfo(solutionSystemInfo.FolderPath)
					.GetFiles("AssemblyInfo.cs", SearchOption.AllDirectories)
					.Select(Packages.Parse)
					.Where(x => x != null && packagesId.Contains(x.Title))
					.GroupBy(x => x.Title)
					.ToDictionary(k => k.Key, v => new { Versions = v.Select(y => y.PackageVersion), Packages = v.Select(y => y) })
					.Where(x => x.Value.Packages.Any(y => y.HasNuget))
					.ToArray();

			var packagesWithDifferentVersions = checkPackages.Where(x => x.Value.Versions.Distinct().Count() > 1).ToArray();

			if (packagesWithDifferentVersions.Any())
			{
				ConsoleHelper.WriteLine("Packages with different versions to be fixed");

				return new UpdatePackagesStep();
			}

			var packages =
				checkPackages
					.OrderBy(x => x.Key)
					.Select(x => new PackageWithFramework(x.Key, x.Value.Versions.First(), x.Value.Packages))
					.ToArray();

			return new UpdatePackagesStep(solutionSystemInfo, buildAndRevision, packages, previousVersions);
		}
开发者ID:matteomigliore,项目名称:HSDK,代码行数:29,代码来源:04.UpdateNuspecAndAssemblyInfoStep.cs

示例5: Main

        static void Main(string[] args)
        {
            var options = new Options();
            Parser.Default.ParseArguments(args , options);
            //Get all forders from the current folder
            var rootFolder = options.RootFolder == "" ? Environment.CurrentDirectory : options.RootFolder;
            var folders = new DirectoryInfo(rootFolder).GetDirectories("*.*", SearchOption.AllDirectories);
            var stats = new List<CodeFile>();

            foreach (var d in folders.Where(d => !d.Name.StartsWith(".")))
            {
                //Check if there's a .git folder here and do a git pull if that is asked for
                //if (options.GitPull) GitPull(d);

                //Check if there's a .vbp file here.
                var vbpFiles = d.GetFiles().Where(f => f.Extension.ToLower() == ".vbp");

                //Get all referenced files from the .vbp
                foreach (var vbp in vbpFiles)
                {
                    var codeFiles = GetProjectFiles(vbp);
                    //Parse each file
                    foreach (var codeFile in codeFiles)
                    {
                        var code = new CodeFile(Path.Combine(d.FullName, codeFile));
                        code.Parse();
                        stats.Add(code);
                    }
                }
            }
            if(!string.IsNullOrEmpty(options.ResultFile))
            {
                if(!File.Exists(options.ResultFile))
                {
                    File.WriteAllText(options.ResultFile, "Date\tFiles\tLines\tComments\tMethods" + Environment.NewLine);
                }
                File.AppendAllText(options.ResultFile, string.Format("{0}\t{1}\t{2}\t{3}\t{4}" + Environment.NewLine,
                DateTime.Now,
                stats.Count(),
                stats.Sum(s => s.Lines),
                stats.Sum(c => c.Comments),
                stats.Sum(m => m.Methods)
                ));
            }
            //Present the result
            if (!options.Silent)
            {
                Console.WriteLine(string.Format("Files:{0} Lines:{1} Comments:{2} Methods:{3}",
                    stats.Count(),
                    stats.Sum(s => s.Lines),
                    stats.Sum(c => c.Comments),
                    stats.Sum(m => m.Methods)
                    ));
            }
        }
开发者ID:idstam,项目名称:vb6counter,代码行数:55,代码来源:Program.cs

示例6: GetFolders

        public IEnumerable<DirectoryInfo> GetFolders(string folder, string[] filter)
        {
            var path = IOHelper.MapPath("~/" + folder.TrimStart('~', '/'));
            if (filter != null && filter[0] != ".")
            {
                IEnumerable<DirectoryInfo> dirs = new DirectoryInfo(path).EnumerateDirectories();
                return dirs.Where(d => d.EnumerateFiles().Where(f => filter.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)).Any());
            }

            return new DirectoryInfo(path).GetDirectories("*");
        }
开发者ID:vnbaaij,项目名称:umbraco7-filepicker,代码行数:11,代码来源:FilePickerApiController.cs

示例7: Run

 public override bool Run()
 {
     if (base.Run())
     {
         DebugInfo.Add("xbl generator");
         var directoryFiles = new DirectoryInfo(this.ApiOutputDirectory).GetFiles("*.xml").Where(f => !f.Name.StartsWith("_"));
         this.ProfileFile = directoryFiles.SingleOrDefault(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "profile")));
         this.GamesFile = directoryFiles.SingleOrDefault(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "games")));
         this.GameFiles = directoryFiles.Where(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "achievements-")));
         return true;
     }
     return false;
 }
开发者ID:JamesSkemp,项目名称:VideoGamesSpa,代码行数:13,代码来源:BaseXblGenerator.cs

示例8: Main

        static int Main(string[] args)
        {
            var containerBuilder = new ContainerBuilder();

            var allAssemblies = new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*.dll").Select(x => Assembly.LoadFile(x.FullName));
            var assemblies = allAssemblies.Where(x => x.GetTypes().Any(t => t.IsAssignableTo<RxDemoModule>())).ToArray();

            containerBuilder.RegisterAssemblyModules(assemblies);

            var container = containerBuilder.Build();


            new MainWindow(container.Resolve<IList<IDemo>>()).ShowDialog();
            return 0;
        }
开发者ID:badamiak,项目名称:RxDemo,代码行数:15,代码来源:RxDemoEntryPoint.cs

示例9: ArtBuilder

        public Tile[,] ArtBuilder(string path)
        {
            var folderPath = path.ToMapPath();
            var images = new DirectoryInfo(folderPath).GetFiles().OnlyImages();
            var config = ConfigService.Generate(folderPath);

            return images
                .Where(FilterImages)
                .Select(x => new Tile(x))
                .Aggregate(new Tile[config.Width, config.Height], (acc, tile) =>
                {
                    acc[tile.Position.X, tile.Position.Y] = tile;

                    return acc;
                });
        }
开发者ID:EricFreeman,项目名称:Collab,代码行数:16,代码来源:ArtController.cs

示例10: GetEndpointName

		static string GetEndpointName(string path)
		{		
			var assemblyFiles = new DirectoryInfo(path).GetFiles("*.dll", SearchOption.AllDirectories)
				.Union(new DirectoryInfo(path).GetFiles("*.exe", SearchOption.AllDirectories));

			assemblyFiles = assemblyFiles.Where(f => !defaultAssemblyExclusions.Any(exclusion => f.Name.ToLower().StartsWith(exclusion)));			

			var results = new List<Assembly>();
			foreach (var assemblyFile in assemblyFiles)
			{
				try
				{
					var pd = new ProxyDomain();
					var assembly = pd.GetAssembly(assemblyFile.FullName);
					assembly.GetTypes();
					results.Add(assembly);
				}
				catch(Exception e)
				{
					
				}
			}


			var endPointType = ScanAssembliesForEndpoints(results).FirstOrDefault();

			if (endPointType == null)
			{
				throw new Exception(string.Format("No implementation of IConfigureThisEndpoint found in {0}", path));
			}

			//Stolen from https://github.com/NServiceBus/NServiceBus/blob/master/src/hosting/NServiceBus.Hosting.Windows/Program.cs
			var endpointConfiguration = Activator.CreateInstance(endPointType);
			var endpointName = endpointConfiguration.GetType().Namespace;

			var arr = endpointConfiguration.GetType().GetCustomAttributes(typeof(EndpointNameAttribute), false);
			if (arr.Length == 1)
				endpointName = (arr[0] as EndpointNameAttribute).Name;

			if (endpointConfiguration is INameThisEndpoint)
				endpointName = (endpointConfiguration as INameThisEndpoint).GetName();

			return endpointName;
		}
开发者ID:glennslaven,项目名称:NserviceBus.Instrumentation,代码行数:44,代码来源:ServiceLoader.cs

示例11: FindSolution

 public static FileInfo FindSolution(string path)
 {
     var solutions =  new DirectoryInfo(path).GetFiles("*.sln", SearchOption.AllDirectories);
     if (solutions.Length == 0)
         throw new Exception("No solution found");
     if (solutions.Length == 1)
         return solutions.First();
     // candidates.Length > 1
     var candidatesByDepth = solutions.GroupBy(x => x.FullName.Count(ch => ch == '/')).ToList();
     var minKey2 = candidatesByDepth.Min(x => x.Key);
     var topLevelCandidates = candidatesByDepth.First(x => x.Key == minKey2);
     if (topLevelCandidates.Count() == 1)
         return topLevelCandidates.First();
     //TopLevelCandidates > 1
     var dirName = Path.GetFileName(path);
     var matchesName = solutions.Where(x => x.Name == dirName).ToList();
     if (matchesName.Count == 1)
         return matchesName.First();
     throw new Exception("Could not find solution");
 }
开发者ID:davidkron,项目名称:DevArch,代码行数:20,代码来源:Program.cs

示例12: Scan

            /// <summary>
            /// Scans the given path for image files and creates a hash for every element found.
            /// </summary>
            /// <param name="path">The directory to search through.</param>
            /// <param name="checkSubdirs">Include subdirectories?</param>
            /// <param name="minDate">Ignore files older than this date.</param>
            /// <returns>Returns a dictionary with the FileInfo-object of the file as key and its hash as value.</returns>
            private Dictionary<FileInfo, ulong> Scan(string path, bool checkSubdirs, DateTime minDate)
            {
                #region Scan subdirs or not
		            SearchOption __options;
                    if (checkSubdirs) __options = SearchOption.AllDirectories;
                    else __options = SearchOption.TopDirectoryOnly;
	            #endregion
                
                //Get all files
                var __files = new DirectoryInfo(path).GetFiles(new string[] { "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp" }, __options).ToList();

                #region Filter according to a given date
                    if (minDate != null)
                        __files = __files.Where(f => DateTime.Compare(f.LastWriteTime, minDate) >= 0).ToList();
                #endregion

                State.Max = __files.Count;

                //todo: Because this is a parallel operation, the ConcurrentDictionary class is used instead of the standard Dictionary (which is not thread-safe) 
                //Critical issue, because doing this parallel saves a huge amount of time
                //var __images = new ConcurrentDictionary<FileInfo, ulong>();
                //__files.AsParallel().ForAll((f) => 
                var __images = new Dictionary<FileInfo, ulong>();
                __files.ToList().ForEach((f) => 
                {
                    //Calling the respective overridden method to create a hash (the case where the key already exists can't happen, so it's not implemented properly)
                    __images.Add(f, GetHash(f.FullName));
                    //Update the State to give information about the current image
                    State.Current = f.Name;
                    State.Count = __files.IndexOf(f) + 1;
                });
                return __images;
            }
开发者ID:Sekagra,项目名称:Doppelganger,代码行数:40,代码来源:ImageFinderBase.cs

示例13: Configure

 public void Configure(IContainer container)
 {
     var files = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).EnumerateFiles("*.dll");
     if (files.Where(file => !IsCoreAssembly(file)).Any(TryLoadConfigurator))
         _configurator.Configure(container);
 }
开发者ID:percramer,项目名称:pjsip4net,代码行数:6,代码来源:DynamicApiConfigurator.cs

示例14: FindLocalCache

 /// <summary>
 /// Find a local directory that has been created and is, thus, accessible and good where we can
 /// cache a dataset.
 /// </summary>
 /// <param name="dirCacheLocations">List of locations to look at</param>
 /// <returns></returns>
 private static DirectoryInfo FindLocalCache(DirectoryInfo[] dirCacheLocations)
 {
     return dirCacheLocations
         .Where(d => d.Exists)
         .FirstOrDefault();
 }
开发者ID:LHCAtlas,项目名称:AtlasSSH,代码行数:12,代码来源:LocalMachine.cs

示例15: GetCachedChannelItemMediaSources

        public IEnumerable<MediaSourceInfo> GetCachedChannelItemMediaSources(IChannelMediaItem item)
        {
            var filenamePrefix = item.Id.ToString("N");
            var parentPath = Path.Combine(ChannelDownloadPath, item.ChannelId);

            try
            {
                var files = new DirectoryInfo(parentPath).EnumerateFiles("*", SearchOption.TopDirectoryOnly);

                if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
                {
                    files = files.Where(i => EntityResolutionHelper.IsVideoFile(i.FullName));
                }
                else
                {
                    files = files.Where(i => EntityResolutionHelper.IsAudioFile(i.FullName));
                }

                var file = files
                    .FirstOrDefault(i => i.Name.StartsWith(filenamePrefix, StringComparison.OrdinalIgnoreCase));

                if (file != null)
                {
                    var cachedItem = _libraryManager.ResolvePath(file);

                    if (cachedItem != null)
                    {
                        var hasMediaSources = _libraryManager.GetItemById(cachedItem.Id) as IHasMediaSources;

                        if (hasMediaSources != null)
                        {
                            var source = hasMediaSources.GetMediaSources(true).FirstOrDefault();

                            if (source != null)
                            {
                                source.Type = MediaSourceType.Cache;
                                return new[] { source };
                            }
                        }
                    }
                }
            }
            catch (DirectoryNotFoundException)
            {

            }

            return new List<MediaSourceInfo>();
        }
开发者ID:jmarsh0507,项目名称:MediaBrowser,代码行数:49,代码来源:ChannelManager.cs


注:本文中的System.IO.DirectoryInfo.Where方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。