System.IO.Directory.EnumerateFiles(string, string, System.IO.SearchOption)

Here are the examples of the csharp api System.IO.Directory.EnumerateFiles(string, string, System.IO.SearchOption) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

843 Examples 7

19 View Source File : WikiBuildingDetailProvider.cs
License : MIT License
Project Creator : AnnoDesigner

private WikiBuildingInfoPresets GetUpdatedWikiBuildingInfoList(WikiBuildingInfoPresets wikiBuildingInfoList)
        {
            Console.WriteLine("start parsing infoboxes");

            Stopwatch sw = new Stopwatch();
            sw.Start();

            try
            {
                foreach (var curFile in Directory.EnumerateFiles(PathToExtractedInfoboxesFolder, $"*{FILE_ENDING_INFOBOX}", SearchOption.TopDirectoryOnly))
                {
                    var fileContent = File.ReadAllText(curFile, Encoding.UTF8);
                    var infoboxes = _infoboxParser.GetInfobox(fileContent);

                    if (infoboxes.Count == 1)
                    {
                        var parsedInfobox = infoboxes[0];

                        WikiBuildingInfo foundWikiBuildingInfo;
                        if (parsedInfobox.Region == WorldRegion.Unknown)
                        {
                            foundWikiBuildingInfo = wikiBuildingInfoList.Infos.FirstOrDefault(x => x.Name.Equals(parsedInfobox.Name, StringComparison.OrdinalIgnoreCase));
                        }
                        else
                        {
                            throw new Exception("expected unknown region");
                        }

                        if (foundWikiBuildingInfo is null)
                        {
                            //if (parsedInfobox?.Name.Contains("Road") == true)
                            //{
                            foundWikiBuildingInfo = wikiBuildingInfoList.Infos.FirstOrDefault(x => x.Name.EndsWith(parsedInfobox.Name));
                            if (foundWikiBuildingInfo is null)
                            {
                                var wikiBuildingInfo = CreateNewBuildingInfo(parsedInfobox);
                                wikiBuildingInfoList.Infos.Add(wikiBuildingInfo);
                                continue;

                                //var exception = new Exception("No WikiBuildingInfo found!");
                                //exception.Data.Add(nameof(curFile), curFile);
                                //exception.Data.Add($"{nameof(parsedInfobox)}.{nameof(parsedInfobox.Name)}", parsedInfobox.Name);

                                //logger.Error(exception);
                                //continue;

                                //throw exception;
                                //is page with multiple infoboxes -> not supported yet
                                //continue;
                            }
                            //}
                            else
                            {

                            }
                        }

                        foundWikiBuildingInfo = CopyInfoboxToBuildingInfo(parsedInfobox, foundWikiBuildingInfo);
                    }
                    else if (infoboxes.Count > 1)
                    {
                        foreach (var curInfobox in infoboxes)
                        {
                            //multiple entries possible e.g. "Police Station" or "Museum"
                            var foundWikiBuildingInfo = wikiBuildingInfoList.Infos.FirstOrDefault(x => x.Name.Equals(curInfobox.Name, StringComparison.OrdinalIgnoreCase) && x.Region == curInfobox.Region);
                            if (foundWikiBuildingInfo is null)
                            {
                                //if (curInfobox?.Name.Contains("Road") == true)
                                //{
                                foundWikiBuildingInfo = wikiBuildingInfoList.Infos.FirstOrDefault(x => x.Name.EndsWith(curInfobox.Name));
                                if (foundWikiBuildingInfo is null)
                                {
                                    var exception = new Exception("No WikiBuildingInfo found!");
                                    exception.Data.Add(nameof(curFile), curFile);
                                    exception.Data.Add($"{nameof(curInfobox)}.{nameof(curInfobox.Name)}", curInfobox.Name);

                                    logger.Error(exception);
                                    continue;

                                    //throw exception;

                                    //is page with multiple infoboxes -> not supported yet
                                    //continue;
                                }
                                //}
                                else
                                {

                                }
                            }

                            foundWikiBuildingInfo = CopyInfoboxToBuildingInfo(curInfobox, foundWikiBuildingInfo);
                        }
                    }
                    else
                    {
                        //got no infoboxes
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"error parsing infoboxes");
                Console.WriteLine(ex);
            }

            sw.Stop();
            Console.WriteLine($"finished parsing infoboxes (took {sw.ElapsedMilliseconds} ms)");

            return wikiBuildingInfoList;
        }

19 View Source File : DragAndDropServiceCustom.cs
License : MIT License
Project Creator : AntonyCorbett

private IEnumerable<string> GetSupportedFiles(IDataObject data)
        {
            if (!data.GetDataPresent(DataFormats.FileDrop))
            {
                yield break;
            }

            // Note that you can have more than one file...
            var files = (string[]?)data.GetData(DataFormats.FileDrop);

            if (files != null && files.Length > 0)
            {
                foreach (var file in files)
                {
                    if (Directory.Exists(file))
                    {
                        // a folder rather than a file.
                        foreach (var fileInFolder in Directory.EnumerateFiles(file))
                        {
                            var fileToAdd = GetSupportedFile(fileInFolder);
                            if (fileToAdd != null)
                            {
                                yield return fileToAdd;
                            }
                        }
                    }
                    else
                    {
                        var fileToAdd = GetSupportedFile(file);
                        if (fileToAdd != null)
                        {
                            yield return fileToAdd;
                        }
                    }
                }
            }
        }

19 View Source File : TestHelpers.cs
License : MIT License
Project Creator : airbreather

public static IEnumerable<object[]> GetTestCsvFiles(params string[] pathParts) =>
            from filePath in Directory.EnumerateFiles(Path.Combine(TestCsvFilesFolderPath, Path.Combine(pathParts)), "*.csv", SearchOption.AllDirectories)
            let relativePath = Path.GetRelativePath(TestCsvFilesFolderPath, filePath)
            select new object[] { relativePath };

19 View Source File : DirectoryUtilities.cs
License : GNU General Public License v3.0
Project Creator : amakvana

public static void Copy(string fromFolder, string toFolder, bool overwrite = false)
        {
            Directory
                .EnumerateFiles(fromFolder, "*.*", SearchOption.AllDirectories)
                .AsParallel()
                .ForAll(from =>
                {
                    var to = from.Replace(fromFolder, toFolder);

                    // Create directories if required
                    var toSubFolder = Path.GetDirectoryName(to);
                    if (!string.IsNullOrWhiteSpace(toSubFolder))
                    {
                        Directory.CreateDirectory(toSubFolder);
                    }

                    File.Copy(from, to, overwrite);
                });
        }

19 View Source File : Database.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

private void LoadCustomUnitEntries(string subDirectory)
        {
            BriefingRoom.PrintToLog($"Custom Loading {subDirectory.ToLowerInvariant()}...");

            string directory = $"{BRPaths.CUSTOMDATABASE}{subDirectory}";
            if (!Directory.Exists(directory))
                return;

            Type dbType = typeof(DBEntryUnit);
            string shortTypeName = dbType.Name.Substring(7).ToLowerInvariant();

            foreach (string filePath in Directory.EnumerateFiles(directory, "*.ini", SearchOption.AllDirectories))
            {
                string id = Path.GetFileNameWithoutExtension(filePath).Replace(",", "").Trim(); // No commas in file names, so we don't break comma-separated arrays

                var entry = new DBEntryUnit();
                if (!entry.Load(this, id, filePath)) continue;
                if (DBEntries[dbType].ContainsKey(id))
                {
                    ((DBEntryUnit)DBEntries[dbType][id]).Merge(entry);
                    BriefingRoom.PrintToLog($"Updated {shortTypeName} \"{id}\"");

                } else {
                    DBEntries[dbType].Add(id, entry);
                    BriefingRoom.PrintToLog($"Loaded {shortTypeName} \"{id}\"");
                }
            }
            BriefingRoom.PrintToLog($"Found {DBEntries[dbType].Count} custom database entries of type \"{typeof(DBEntryUnit).Name}\"");

            bool mustHaveAtLeastOneEntry = true;
            if ((dbType == typeof(DBEntryDefaultUnitList)) ||
                (dbType == typeof(DBEntryFeatureMission)) ||
                (dbType == typeof(DBEntryFeatureObjective)))
                mustHaveAtLeastOneEntry = false;

            // If a required database type has no entries, raise an error.
            if ((DBEntries[dbType].Count == 0) && mustHaveAtLeastOneEntry)
                BriefingRoom.PrintToLog($"No valid database entries found in the \"{subDirectory}\" directory", LogMessageErrorLevel.Error);
        }

19 View Source File : Platform.Posix.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
			{
				if (string.IsNullOrWhiteSpace(libraryName))
				{
					throw new ArgumentException("A valid library name is expected.", nameof(libraryName));
				}

				// Now look: This method should ExpandPaths on LibraryPaths.
				// That being said, it should just enumerate
				// Path, AppBase, Arch, Compiler, LibraryName, Extension

				// Secondly, this method should try each /lib/x86_64-linux-gnu/libload.so.2 to load,
				// Third, this method should try EmbeddedResources,
				// Finally, this method fails, telling the user all libraryPaths searched.

				var libraryPaths = new List<string>(Platform.LibraryPaths);

				Platform.ExpandPaths(libraryPaths, "{Path}", EnumerateLibLdConf("/etc/ld.so.conf"));

				var PATHs = new List<string>();
				PATHs.Add(EnsureNotEndingSlash(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location)));
				PATHs.AddRange(EnumerateLibLdPATH());
				Platform.ExpandPaths(libraryPaths, "{DllPath}", PATHs.ToArray());

				Platform.ExpandPaths(libraryPaths, "{AppBase}", EnsureNotEndingSlash(
						AppDomain.CurrentDomain.BaseDirectory));

				Platform.ExpandPaths(libraryPaths, "{LibraryName}", libraryName);

				// Platform.ExpandPaths(libraryPaths, "{Ext}", Platform.LibraryFileExtension);

				string architecture;
				string[] architecturePaths = null;
				if (Platform.Architecture == ImageFileMachine.I386 && Environment.Is64BitProcess) 
				{
					architecture = "amd64";
				}
				else {
					architecture = Enum.GetName(typeof(ImageFileMachine), Platform.Architecture).ToLower();
				}
				if (architecture == "i386") architecturePaths = new string[] { "i386", "x86" };
				if (architecture == "amd64") architecturePaths = new string[] { "amd64", "x64" };
				if (architecturePaths == null) architecturePaths = new string[] { architecture };
				Platform.ExpandPaths(libraryPaths, "{Arch}", architecturePaths);

				// Expand Compiler
				Platform.ExpandPaths(libraryPaths, "{Compiler}", Platform.Compiler);

				// Now TRY the enumerated Directories for libFile.so.*

				string traceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);

				foreach (string libraryPath in libraryPaths)
				{

				    IEnumerable<string> files;
				    if (libraryPath.Contains("/"))
				    {

				        string folder = null;
				        string filesPattern = libraryPath;
				        int filesPatternI;
				        if (-1 < (filesPatternI = filesPattern.LastIndexOf('/')))
				        {
				            folder = filesPattern.Substring(0, filesPatternI + 1);
				            filesPattern = filesPattern.Substring(filesPatternI + 1);
				        }

				        if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;

				        files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
				    }
				    else
				    {
				        files = Enumerable.Repeat(libraryPath, 1);
				    }

				    foreach (string file in files)
					{
						// Finally, I am really loading this file
						SafeLibraryHandle handle = OpenHandle(file);

						if (!handle.IsNullOrInvalid())
						{
							// This is Platform.Posix. In mono, just dlopen'ing the library doesn't work.
							// Using DllImport("__Internal", EntryPoint = "mono_dllmap_insert") to get mono on the path.
							MonoDllMapInsert(libraryName, file);

							Trace.TraceInformation(string.Format("{0} Loaded binary \"{1}\"", 
								traceLabel, file));

							return new UnmanagedLibrary(libraryName, handle);
						}
						else
						{
							Exception nativeEx = GetLastLibraryError();
							Trace.TraceInformation(string.Format("{0} Custom binary \"{1}\" not loaded: {2}", 
								traceLabel, file, nativeEx.Message));
						}
					}					
				}

				// Search ManifestResources for fileName.arch.ext
				// TODO: Enumerate ManifestResources for ZeroMQ{Arch}{Compiler}{LibraryName}{Ext}.so.*
				string resourceName = string.Format("ZeroMQ.{0}.{1}{2}", libraryName, architecture, ".so");
				string tempPath = Path.Combine(Path.GetTempPath(), resourceName);

				if (ExtractManifestResource(resourceName, tempPath))
				{
					// TODO: need syscall_chmod_execute(path); ?
					SafeLibraryHandle handle = OpenHandle(tempPath);

					if (!handle.IsNullOrInvalid())
					{
						MonoDllMapInsert(libraryName, tempPath);

						Trace.TraceInformation(string.Format("{0} Loaded binary from EmbeddedResource \"{1}\" from \"{2}\".", 
							traceLabel, resourceName, tempPath));
						
						return new UnmanagedLibrary(libraryName, handle);
					}					
					else
					{
						Trace.TraceWarning(string.Format("{0} Unable to run the extracted EmbeddedResource \"{1}\" from \"{2}\".",
							traceLabel, resourceName, tempPath));
					}
				}
				else
				{
					Trace.TraceWarning(string.Format("{0} Unable to extract the EmbeddedResource \"{1}\" to \"{2}\".",
						traceLabel, resourceName, tempPath));
				}


				var fnf404 = new StringBuilder();
				fnf404.Append(traceLabel);
				fnf404.Append(" Unable to load binary \"");
				fnf404.Append(libraryName);
				fnf404.AppendLine("\" from folders");
				foreach (string path in libraryPaths)
				{
					fnf404.Append("\t");
					fnf404.AppendLine(path);
				}
				fnf404.Append(" Also unable to load binary from EmbeddedResource \"");
				fnf404.Append(resourceName);
				fnf404.Append("\", from temporary path \"");
				fnf404.Append(tempPath);
				fnf404.Append("\". See Trace output for more information.");

				throw new FileNotFoundException(fnf404.ToString());
			}

19 View Source File : PluginCore.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void MigrateTTSCache()
        {
            var oldCacheDir = Path.Combine(
                 Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                 @"anoyetta\ACT");

            var newCacheDir = Path.Combine(
                oldCacheDir,
                "tts cache");

            if (!Directory.Exists(newCacheDir))
            {
                Directory.CreateDirectory(newCacheDir);
            }

            foreach (var file in Directory.EnumerateFiles(
                oldCacheDir, "*.wav", SearchOption.TopDirectoryOnly))
            {
                var dest = Path.Combine(
                    newCacheDir,
                    Path.GetFileName(file));

                if (File.Exists(dest))
                {
                    File.Delete(dest);
                }

                File.Move(file, dest);
            }
        }

19 View Source File : Runner.cs
License : MIT License
Project Creator : actions

public async Task<int> ExecuteCommand(CommandSettings command)
        {
            try
            {
                VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);

                _inConfigStage = true;
                _completedCommand.Reset();
                _term.CancelKeyPress += CtrlCHandler;

                //register a SIGTERM handler
                HostContext.Unloading += Runner_Unloading;

                // TODO Unit test to cover this logic
                Trace.Info(nameof(ExecuteCommand));
                var configManager = HostContext.GetService<IConfigurationManager>();

                // command is not required, if no command it just starts if configured

                // TODO: Invalid config prints usage

                if (command.Help)
                {
                    PrintUsage(command);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Version)
                {
                    _term.WriteLine(BuildConstants.RunnerPackage.Version);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Commit)
                {
                    _term.WriteLine(BuildConstants.Source.CommitHash);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Check)
                {
                    var url = command.GetUrl();
                    var pat = command.GetGitHubPersonalAccessToken(required: true);
                    var checkExtensions = HostContext.GetService<IExtensionManager>().GetExtensions<ICheckExtension>();
                    var sortedChecks = checkExtensions.OrderBy(x => x.Order);
                    foreach (var check in sortedChecks)
                    {
                        _term.WriteLine($"**********************************************************************************************************************");
                        _term.WriteLine($"**  Check:               {check.CheckName}");
                        _term.WriteLine($"**  Description:         {check.CheckDescription}");
                        _term.WriteLine($"**********************************************************************************************************************");
                        var result = await check.RunCheck(url, pat);
                        if (!result)
                        {
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**                                            F A I L                                                               **");
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**********************************************************************************************************************");
                            _term.WriteLine($"** Log: {check.CheckLog}");
                            _term.WriteLine($"** Help Doc: {check.HelpLink}");
                            _term.WriteLine($"**********************************************************************************************************************");
                        }
                        else
                        {
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**                                            P A S S                                                               **");
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**********************************************************************************************************************");
                            _term.WriteLine($"** Log: {check.CheckLog}");
                            _term.WriteLine($"**********************************************************************************************************************");
                        }

                        _term.WriteLine();
                        _term.WriteLine();
                    }

                    return Constants.Runner.ReturnCode.Success;
                }

                // Configure runner prompt for args if not supplied
                // Unattended configure mode will not prompt for args if not supplied and error on any missing or invalid value.
                if (command.Configure)
                {
                    try
                    {
                        await configManager.ConfigureAsync(command);
                        return Constants.Runner.ReturnCode.Success;
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                }

                // remove config files, remove service, and exit
                if (command.Remove)
                {
                    try
                    {
                        await configManager.UnconfigureAsync(command);
                        return Constants.Runner.ReturnCode.Success;
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                }

                _inConfigStage = false;

                // warmup runner process (JIT/CLR)
                // In scenarios where the runner is single use (used and then thrown away), the system provisioning the runner can call `Runner.Listener --warmup` before the machine is made available to the pool for use.
                // this will optimizes the runner process startup time.
                if (command.Warmup)
                {
                    var binDir = HostContext.GetDirectory(WellKnownDirectory.Bin);
                    foreach (var replacedemblyFile in Directory.EnumerateFiles(binDir, "*.dll"))
                    {
                        try
                        {
                            Trace.Info($"Load replacedembly: {replacedemblyFile}.");
                            var replacedembly = replacedembly.LoadFrom(replacedemblyFile);
                            var types = replacedembly.GetTypes();
                            foreach (Type loadedType in types)
                            {
                                try
                                {
                                    Trace.Info($"Load methods: {loadedType.FullName}.");
                                    var methods = loadedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                                    foreach (var method in methods)
                                    {
                                        if (!method.IsAbstract && !method.ContainsGenericParameters)
                                        {
                                            Trace.Verbose($"Prepare method: {method.Name}.");
                                            RuntimeHelpers.PrepareMethod(method.MethodHandle);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Trace.Error(ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Error(ex);
                        }
                    }

                    return Constants.Runner.ReturnCode.Success;
                }

                RunnerSettings settings = configManager.LoadSettings();

                var store = HostContext.GetService<IConfigurationStore>();
                bool configuredreplacedervice = store.IsServiceConfigured();

                // Run runner
                if (command.Run) // this line is current break machine provisioner.
                {
                    // Error if runner not configured.
                    if (!configManager.IsConfigured())
                    {
                        _term.WriteError("Runner is not configured.");
                        PrintUsage(command);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }

                    Trace.Verbose($"Configured as service: '{configuredreplacedervice}'");

                    //Get the startup type of the runner i.e., autostartup, service, manual
                    StartupType startType;
                    var startupTypereplacedtring = command.GetStartupType();
                    if (string.IsNullOrEmpty(startupTypereplacedtring) && configuredreplacedervice)
                    {
                        // We need try our best to make the startup type accurate
                        // The problem is coming from runner autoupgrade, which result an old version service host binary but a newer version runner binary
                        // At that time the servicehost won't preplaced --startuptype to Runner.Listener while the runner is actually running as service.
                        // We will guess the startup type only when the runner is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
                        Trace.Info($"Try determine runner startup type base on console redirects.");
                        startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
                    }
                    else
                    {
                        if (!Enum.TryParse(startupTypereplacedtring, true, out startType))
                        {
                            Trace.Info($"Could not parse the argument value '{startupTypereplacedtring}' for StartupType. Defaulting to {StartupType.Manual}");
                            startType = StartupType.Manual;
                        }
                    }

                    Trace.Info($"Set runner startup type - {startType}");
                    HostContext.StartupType = startType;

                    if (command.RunOnce)
                    {
                        _term.WriteLine("Warning: '--once' is going to be deprecated in the future, please consider using '--ephemeral' during runner registration.", ConsoleColor.Yellow);
                        _term.WriteLine("https://docs.github.com/en/actions/hosting-your-own-runners/autoscaling-with-self-hosted-runners#using-ephemeral-runners-for-autoscaling", ConsoleColor.Yellow);
                    }

                    // Run the runner interactively or as service
                    return await RunAsync(settings, command.RunOnce || settings.Ephemeral);
                }
                else
                {
                    PrintUsage(command);
                    return Constants.Runner.ReturnCode.Success;
                }
            }
            finally
            {
                _term.CancelKeyPress -= CtrlCHandler;
                HostContext.Unloading -= Runner_Unloading;
                _completedCommand.Set();
            }
        }

19 View Source File : TrainerSettings.cs
License : MIT License
Project Creator : architdate

public static void LoadTrainerDatabaseFromPath(string path)
        {
            if (!Directory.Exists(path))
                return;
            var files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories);
            foreach (var f in files)
            {
                var len = new FileInfo(f).Length;
                if (!PKX.IsPKM(len))
                    return;
                var data = File.ReadAllBytes(f);
                var pk = PKMConverter.GetPKMfromBytes(data);
                if (pk != null)
                    Database.Register(pk);
            }
        }

19 View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions

public async Task<long> CopyToContainerAsync(
            RunnerActionPluginExecutionContext context,
            String source,
            CancellationToken cancellationToken)
        {
            //set maxConcurrentUploads up to 2 until figure out how to use WinHttpHandler.MaxConnectionsPerServer modify DefaultConnectionLimit
            int maxConcurrentUploads = Math.Min(Environment.ProcessorCount, 2);
            //context.Output($"Max Concurrent Uploads {maxConcurrentUploads}");

            List<String> files;
            if (File.Exists(source))
            {
                files = new List<String>() { source };
                _sourceParentDirectory = Path.GetDirectoryName(source);
            }
            else
            {
                files = Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories).ToList();
                _sourceParentDirectory = source.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            }

            context.Output($"Uploading {files.Count()} files");
            using (_uploadCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                // hook up reporting event from file container client.
                _fileContainerHttpClient.UploadFileReportTrace += UploadFileTraceReportReceived;
                _fileContainerHttpClient.UploadFileReportProgress += UploadFileProgressReportReceived;

                try
                {
                    // try upload all files for the first time.
                    UploadResult uploadResult = await ParallelUploadAsync(context, files, maxConcurrentUploads, _uploadCancellationTokenSource.Token);

                    if (uploadResult.RetryFiles.Count == 0)
                    {
                        // all files have been upload succeed.
                        context.Output("File upload complete.");
                        return uploadResult.TotalFileSizeUploaded;
                    }
                    else
                    {
                        context.Output($"{uploadResult.RetryFiles.Count} files failed to upload, retry these files after a minute.");
                    }

                    // Delay 1 min then retry failed files.
                    for (int timer = 60; timer > 0; timer -= 5)
                    {
                        context.Output($"Retry file upload after {timer} seconds.");
                        await Task.Delay(TimeSpan.FromSeconds(5), _uploadCancellationTokenSource.Token);
                    }

                    // Retry upload all failed files.
                    context.Output($"Start retry {uploadResult.RetryFiles.Count} failed files upload.");
                    UploadResult retryUploadResult = await ParallelUploadAsync(context, uploadResult.RetryFiles, maxConcurrentUploads, _uploadCancellationTokenSource.Token);

                    if (retryUploadResult.RetryFiles.Count == 0)
                    {
                        // all files have been upload succeed after retry.
                        context.Output("File upload complete after retry.");
                        return uploadResult.TotalFileSizeUploaded + retryUploadResult.TotalFileSizeUploaded;
                    }
                    else
                    {
                        throw new Exception("File upload failed even after retry.");
                    }
                }
                finally
                {
                    _fileContainerHttpClient.UploadFileReportTrace -= UploadFileTraceReportReceived;
                    _fileContainerHttpClient.UploadFileReportProgress -= UploadFileProgressReportReceived;
                }
            }
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : Alprog

public static DateTime GetLastWriteTimeInDirectory(string path)
        {
            var maxTime = DateTime.MinValue;
            foreach (var filePath in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories))
            {
                if (filePath.EndsWith(".meta"))
                {
                    continue;
                }
                var time = File.GetLastWriteTimeUtc(filePath);
                if (time > maxTime)
                {
                    maxTime = time;
                }
            }
            return maxTime;
        }

19 View Source File : ExtensionMethods.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public static bool VehicleModelIsELS(Model model)
        {
            try
            {
                if (vehicleModelELSCache.ContainsKey(model))
                {
                    return vehicleModelELSCache[model];
                }

                if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "ELS")))
                {
                    // no ELS installation at all
                    vehicleModelELSCache.Add(model, false);
                    return false;
                }

                IEnumerable<string> elsFiles = Directory.EnumerateFiles(
                    Path.Combine(Directory.GetCurrentDirectory(), "ELS"),
                    $"{model.Name}.xml", SearchOption.AllDirectories);

                vehicleModelELSCache.Add(model, elsFiles.Any());
                return vehicleModelELSCache[model];
            }
            catch (Exception e)
            {
                Game.LogTrivial($"Failed to determine if a vehicle model '{model}' was ELS-enabled: {e}");
                return false;
            }
        }

19 View Source File : Serialization.Load.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static void Free(ref GNFS gnfs)
                {
                    if (gnfs.CurrentRelationsProgress.Relations.FreeRelations.Any(lst => lst.Any(rel => !rel.IsPersisted)))
                    {
                        List<List<Relation>> unsaved = gnfs.CurrentRelationsProgress.Relations.FreeRelations.Where(lst => lst.Any(rel => !rel.IsPersisted)).ToList();
                        foreach (List<Relation> solution in unsaved)
                        {
                            Serialization.Save.Object(solution, Path.Combine(gnfs.SaveLocations.SaveDirectory, $"!!UNSAVED__{nameof(RelationContainer.FreeRelations)}.json"));
                        }
                    }

                    gnfs.CurrentRelationsProgress.Relations.FreeRelations.Clear();
                    gnfs.CurrentRelationsProgress.FreeRelationsCounter = 0;

                    IEnumerable<string> freeRelations = Directory.EnumerateFiles(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.FreeRelations)}_*.json");
                    foreach (string solution in freeRelations)
                    {
                        List<Relation> temp = Load.Generic<List<Relation>>(solution);
                        temp.ForEach(rel => rel.IsPersisted = true);
                        gnfs.CurrentRelationsProgress.Relations.FreeRelations.Add(temp);
                        gnfs.CurrentRelationsProgress.FreeRelationsCounter += 1;
                    }
                }

19 View Source File : FileService.cs
License : MIT License
Project Creator : amoscardino

public List<FileMatch> GetFiles(string inputDirectory, bool recurse = false)
        {
            var files = Directory
                    .EnumerateFiles(inputDirectory, "*.*", recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                    .Where(path => !Path.GetFileName(path).StartsWith('.'))
                    .Select(path => new FileMatch { OldPath = path })
                    .OrderBy(match => match.OldPath)
                    .ToList();

            _console.WriteLine($"Found {files.Count} files.");
            _console.WriteLine();

            return files;
        }

19 View Source File : RecordFSRepo.cs
License : Apache License 2.0
Project Creator : acblog

public override IAsyncEnumerable<string> All(CancellationToken cancellationToken = default)
        {
            IEnumerable<string> Inner()
            {
                foreach (var file in Directory.EnumerateFiles(RootPath, "*.md", SearchOption.AllDirectories))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var name = Path.GetRelativePath(RootPath, file);
                    yield return name[0..^3].Replace('\\', '/');
                }
            }
            return Inner().ToAsyncEnumerable();
        }

19 View Source File : WikiBuildingDetailProvider.cs
License : MIT License
Project Creator : AnnoDesigner

private void ExtractInfoboxesFromDetailPages()
        {
            Console.WriteLine("start extracting infoboxes");

            Stopwatch sw = new Stopwatch();
            sw.Start();

            if (!Directory.Exists(PathToExtractedInfoboxesFolder))
            {
                Directory.CreateDirectory(PathToExtractedInfoboxesFolder);
            }

            var filesWithWikiText = Directory.EnumerateFiles(PathToDetailsFolder, $"*{FILE_ENDING_WIKITEXT}", SearchOption.TopDirectoryOnly)
                .Where(x => !Path.GetFileName(x).Equals(FILENAME_MISSING_INFOS, StringComparison.OrdinalIgnoreCase));
            var totalFileCount = filesWithWikiText.Count();
            var fileCounter = 0;

            foreach (var curFile in filesWithWikiText)
            {
                try
                {
                    Console.WriteLine($"extracting infobox {++fileCounter} of {totalFileCount}");

                    var fileContent = File.ReadAllText(curFile, Encoding.UTF8);
                    var extractedInfoboxes = _infoboxExtractor.ExtractInfobox(fileContent);

                    foreach (var curExtractedInfobox in extractedInfoboxes)
                    {
                        var curFileName = Path.GetFileNameWithoutExtension(curFile);

                        if (!string.IsNullOrWhiteSpace(curExtractedInfobox.replacedle))
                        {
                            if (!curExtractedInfobox.replacedle.Equals(curFileName, StringComparison.OrdinalIgnoreCase))
                            {
                                curFileName = curExtractedInfobox.replacedle;
                            }
                        }

                        var destinationFilePath = GetFileNameForInfobox(GetCleanedFilename(curFileName));
                        File.WriteAllText(destinationFilePath, curExtractedInfobox.infobox, Encoding.UTF8);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, $"error extracting infobox: \"{curFile}\"");
                    Console.WriteLine(ex);
                }
            }

            sw.Stop();
            Console.WriteLine($"finished extracting infoboxes (took {sw.ElapsedMilliseconds} ms)");
        }

19 View Source File : Platform.Win32.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
			{
				if (string.IsNullOrWhiteSpace(libraryName))
				{
					throw new ArgumentException("A valid library name is expected.", nameof(libraryName));
				}

				// Now look: This method should ExpandPaths on LibraryPaths.
				// That being said, it should just enumerate
				// Path, AppBase, Arch, Compiler, LibraryName, Extension

				// Secondly, this method should try each /lib/x86_64-linux-gnu/libload.so.2 to load,
				// Third, this method should try EmbeddedResources,
				// Finally, this method fails, telling the user all libraryPaths searched.

				var libraryPaths = new List<string>(Platform.LibraryPaths);

				Platform.ExpandPaths(libraryPaths, "{System32}", Environment.SystemDirectory);
	
				var PATHs = new List<string>();
				PATHs.Add(EnsureNotEndingBackSlash(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location)));
				PATHs.AddRange(EnumeratePATH());
				Platform.ExpandPaths(libraryPaths, "{DllPath}", PATHs);

				Platform.ExpandPaths(libraryPaths, "{AppBase}", EnsureNotEndingBackSlash(
						AppDomain.CurrentDomain.BaseDirectory));

				Platform.ExpandPaths(libraryPaths, "{LibraryName}", libraryName);

				// Platform.ExpandPaths(libraryPaths, "{Ext}", Platform.LibraryFileExtension);

				string architecture;
				string[] architecturePaths = null;
				if (Platform.Architecture == ImageFileMachine.I386 && Environment.Is64BitProcess)
				{
					architecture = "amd64";
				}
				else {
					architecture = Enum.GetName(typeof(ImageFileMachine), Platform.Architecture).ToLower();
				}
				if (architecture == "i386") architecturePaths = new string[] { "i386", "x86" };
				if (architecture == "amd64") architecturePaths = new string[] { "amd64", "x64" };
				if (architecturePaths == null) architecturePaths = new string[] { architecture };
				Platform.ExpandPaths(libraryPaths, "{Arch}", architecturePaths);

				// Expand Compiler
				Platform.ExpandPaths(libraryPaths, "{Compiler}", Platform.Compiler);

				// Now TRY the enumerated Directories for libFile.so.*

				string traceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);

				foreach (string libraryPath in libraryPaths)
				{
					string folder = null;
					string filesPattern = libraryPath;
					int filesPatternI;
					if (-1 < (filesPatternI = filesPattern.LastIndexOf('\\')))
					{
						folder = filesPattern.Substring(0, filesPatternI + 1);
						filesPattern = filesPattern.Substring(filesPatternI + 1);
					}

					if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;

					string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();

					foreach (string file in files)
					{
						// Finally, I am really loading this file
						SafeLibraryHandle handle = OpenHandle(file);

						if (!handle.IsNullOrInvalid())
						{
							Trace.TraceInformation(string.Format("{0} Loaded binary \"{1}\"", 
								traceLabel, file));

							return new UnmanagedLibrary(libraryName, handle);
						}
						else
						{
							Exception nativeEx = GetLastLibraryError();
							Trace.TraceInformation(string.Format("{0} Custom binary \"{1}\" not loaded: {2}", 
								traceLabel, file, nativeEx.Message));
						}
					}
				}

				// Search ManifestResources for fileName.arch.ext
				// TODO: Enumerate ManifestResources for ZeroMQ{Arch}{Compiler}{LibraryName}{Ext}.dll
				string resourceName = string.Format("ZeroMQ.{0}.{1}{2}", libraryName, architecture, ".dll");
				string tempPath = Path.Combine(Path.GetTempPath(), resourceName);

				if (ExtractManifestResource(resourceName, tempPath))
				{
					SafeLibraryHandle handle = OpenHandle(tempPath);

					if (!handle.IsNullOrInvalid())
					{
						Trace.TraceInformation(string.Format("{0} Loaded binary from EmbeddedResource \"{1}\" from \"{2}\".", 
							traceLabel, resourceName, tempPath));
						
						return new UnmanagedLibrary(libraryName, handle);
					}
					else
					{
						Trace.TraceWarning(string.Format("{0} Unable to run the extracted EmbeddedResource \"{1}\" from \"{2}\".",
							traceLabel, resourceName, tempPath));
					}
				}
				else
				{
					Trace.TraceWarning(string.Format("{0} Unable to extract the EmbeddedResource \"{1}\" to \"{2}\".",
						traceLabel, resourceName, tempPath));
				}

				var fnf404 = new StringBuilder();
				fnf404.Append(traceLabel);
				fnf404.Append(" Unable to load binary \"");
				fnf404.Append(libraryName);
				fnf404.AppendLine("\" from folders");
				foreach (string path in libraryPaths)
				{
					fnf404.Append("\t");
					fnf404.AppendLine(path);
				}
				fnf404.Append(" Also unable to load binary from EmbeddedResource \"");
				fnf404.Append(resourceName);
				fnf404.Append("\", from temporary path \"");
				fnf404.Append(tempPath);
				fnf404.Append("\". See Trace output for more information.");

				throw new FileNotFoundException(fnf404.ToString());
			}

19 View Source File : SharlayanController.cs
License : MIT License
Project Creator : anoyetta

private static void ClearLocalCaches()
        {
            var dir = Directory.GetCurrentDirectory();
            foreach (var f in LocalCacheFiles)
            {
                foreach (var file in Directory.EnumerateFiles(dir, f))
                {
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }
                }
            }
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static void Main(string[] args)
        {

            int ruleCount = 0;
            int gradientMax = 0;
            Parser.Default.ParseArguments<Options>(args)
                .WithParsed(o =>
                {
                    LoadConfig(o);
                    if (!o.Suricata)
                    {
                        LoadMismatchSearchMatrix(o);
                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.yml", SearchOption.AllDirectories))
                        {
                            try
                            {
                                var dict = DeserializeYamlFile(ruleFilePath, o);
                                if (dict != null && dict.ContainsKey("tags"))
                                {
                                    ruleCount++;
                                    var tags = dict["tags"];
                                    var categories = new List<string>();
                                    string lastEntry = null;
                                    foreach (string tag in tags)
                                    {
                                        //If its the technique id entry, then this adds the file name to the techniques map
                                        if (tag.ToLower().StartsWith("attack.t"))
                                        {
                                            var techniqueId = tag.Replace("attack.", "").ToUpper();
                                            if (!techniques.ContainsKey(techniqueId))
                                                techniques[techniqueId] = new List<string>();
                                            techniques[techniqueId].Add(ruleFilePath.Split("\\").Last());
                                            if (techniques.Count > gradientMax)
                                                gradientMax = techniques.Count;
                                            //then if there are any categories so far, it checks for a mismatch for each one
                                            if (categories.Count > 0 && o.Warning)
                                            {
                                                foreach (string category in categories)
                                                    if (!(mismatchSearchMatrix.ContainsKey(techniqueId) && mismatchSearchMatrix[techniqueId].Contains(category)))
                                                        mismatchWarnings.Add($"MITRE ATT&CK technique ({techniqueId}) and tactic ({category}) mismatch in rule: {ruleFilePath.Split("\\").Last()}");
                                            }
                                        }
                                        else
                                        {
                                            //if its the start of a new technique block, then clean categories and adds first category
                                            if (lastEntry == null || lastEntry.StartsWith("attack.t"))
                                                categories = new List<string>();
                                            categories.Add(
                                                tag.Replace("attack.", "")
                                                .Replace("_", "-")
                                                .ToLower());
                                        }
                                        lastEntry = tag;
                                    }
                                }
                            }
                            catch (YamlException e)
                            {
                                Console.Error.WriteLine($"Ignoring rule {ruleFilePath} (parsing failed)");
                            }
                        }

                        WriteSigmaFileResult(o, gradientMax, ruleCount, techniques);
                        PrintWarnings();
                    }
                    else
                    {

                        List<Dictionary<string, List<string>>> res = new List<Dictionary<string, List<string>>>();

                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.rules", SearchOption.AllDirectories))
                        {
                            res.Add(ParseRuleFile(ruleFilePath));
                        }

                        WriteSuricataFileResult(o,
                            res
                                .SelectMany(dict => dict)
                                .ToLookup(pair => pair.Key, pair => pair.Value)
                                .ToDictionary(group => group.Key,
                                              group => group.SelectMany(list => list).ToList()));
                    }

                });
        }

19 View Source File : LegalityTests.cs
License : MIT License
Project Creator : architdate

private static void VerifyAll(string folder, string name, bool isValid)
        {
            var path = Path.Combine(folder, name);
            Directory.Exists(path).Should().BeTrue($"the specified test directory at '{path}' should exist");

            var files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                var fi = new FileInfo(file);
                var pk = GetPKM(file, fi);

                // double check initial state
                var la = new Legalityreplacedysis(pk);
                la.Valid.Should().Be(isValid, $"because the file '{fi.Directory.Name}\\{fi.Name}' should be {(isValid ? "Valid" : "Invalid")}");

                // try legalizing, should end up as legal
                var updated = pk.Legalize();
                var la2 = new Legalityreplacedysis(updated);
                la2.Valid.Should().Be(true, $"because the file '{fi.Directory.Name}\\{fi.Name}' should be legal");
            }
        }

19 View Source File : TestHelpers.cs
License : MIT License
Project Creator : airbreather

public static IEnumerable<object[]> GetTestCsvFilesWithChunkLengthsAndDelimiters(params string[] pathParts) =>
            from filePath in Directory.EnumerateFiles(Path.Combine(TestCsvFilesFolderPath, Path.Combine(pathParts)), "*.csv", SearchOption.AllDirectories)
            let relativePath = Path.GetRelativePath(TestCsvFilesFolderPath, filePath)
            from chunkLength in TestChunkLengths
            from delimiter in TestDelimiters
            select new object[] { relativePath, chunkLength, delimiter };

19 View Source File : Database.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

private void LoadEntries<T>(string subDirectory) where T : DBEntry, new()
        {
            BriefingRoom.PrintToLog($"Loading {subDirectory.ToLowerInvariant()}...");

            string directory = $"{BRPaths.DATABASE}{subDirectory}";
            if (!Directory.Exists(directory))
                throw new Exception($"Directory {directory} not found.");

            Type dbType = typeof(T);
            string shortTypeName = dbType.Name.Substring(7).ToLowerInvariant();

            if (!DBEntries.ContainsKey(dbType))
                DBEntries.Add(dbType, new Dictionary<string, DBEntry>(StringComparer.InvariantCultureIgnoreCase));

            DBEntries[dbType].Clear();

            foreach (string filePath in Directory.EnumerateFiles(directory, "*.ini", SearchOption.AllDirectories))
            {
                string id = Path.GetFileNameWithoutExtension(filePath).Replace(",", "").Trim(); // No commas in file names, so we don't break comma-separated arrays

                if (DBEntries[dbType].ContainsKey(id)) continue;
                T entry = new T();
                if (!entry.Load(this, id, filePath)) continue;
                DBEntries[dbType].Add(id, entry);
                BriefingRoom.PrintToLog($"Loaded {shortTypeName} \"{id}\"");
            }
            BriefingRoom.PrintToLog($"Found {DBEntries[dbType].Count} database entries of type \"{typeof(T).Name}\"");

            bool mustHaveAtLeastOneEntry = true;
            if ((dbType == typeof(DBEntryDefaultUnitList)) ||
                (dbType == typeof(DBEntryFeatureMission)) ||
                (dbType == typeof(DBEntryFeatureObjective)))
                mustHaveAtLeastOneEntry = false;

            // If a required database type has no entries, raise an error.
            if ((DBEntries[dbType].Count == 0) && mustHaveAtLeastOneEntry)
                BriefingRoom.PrintToLog($"No valid database entries found in the \"{subDirectory}\" directory", LogMessageErrorLevel.Error);
        }

19 View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott

protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
            {
                string unmanagedDllPath = Directory.EnumerateFiles(
                    this.loaderTask.UnmanagedDllDirectory,
                    $"{unmanagedDllName}.*").Concat(
                        Directory.EnumerateFiles(
                            this.loaderTask.UnmanagedDllDirectory,
                            $"lib{unmanagedDllName}.*"))
                    .FirstOrDefault();
                if (unmanagedDllPath != null)
                {
                    return this.LoadUnmanagedDllFromPath(unmanagedDllPath);
                }

                return base.LoadUnmanagedDll(unmanagedDllName);
            }

19 View Source File : LicenseHeader.cs
License : Apache License 2.0
Project Creator : akarnokd

private static void VisitSources(string path)
        {
            var found = false;

            var ci = Environment.GetEnvironmentVariable("CI") != null;

            var sb = new StringBuilder();

            foreach (var entry in Directory.EnumerateFiles(path, "*.cs", SearchOption.AllDirectories))
            {
                var entryForward = entry.Replace("\\", "/");
                if (entryForward.Contains("replacedemblyInfo") 
                    || entryForward.Contains("Temporary")
                    || entryForward.Contains("/obj/")
                    || entryForward.Contains("/Debug/")
                    || entryForward.Contains("/Release/"))
                {
                    continue;
                }
                
                var text = File.ReadAllText(entry, Encoding.UTF8);
                if (!text.Contains("\r\n"))
                {
                    text = text.Replace("\n", "\r\n");
                }
                if (!text.StartsWith(HeaderLines))
                {
                    sb.Append(entry).Append("\r\n");
                    found = true;
                    if (!ci)
                    {
                        File.WriteAllText(entry, HeaderLines + text, Encoding.UTF8);
                    }
                }
            }

            if (found)
            {
                throw new InvalidOperationException("Missing header found and added. Please rebuild the project of " + path + "\r\n" + sb);
            }
        }

19 View Source File : ProjectSet.cs
License : MIT License
Project Creator : adamant

private static async Task<PackageIL?> Build(
            AdamantCompiler compiler,
            Project project,
            Task<FixedDictionary<Project, Task<PackageIL?>>> projectBuildsTask,
            object consoleLock)
        {
            var projectBuilds = await projectBuildsTask.ConfigureAwait(false);
            var sourceDir = Path.Combine(project.Path, "src");
            var sourcePaths = Directory.EnumerateFiles(sourceDir, "*.ad", SearchOption.AllDirectories);
            // Wait for the references, unfortunately, this requires an ugly loop.
            var referenceTasks = project.References.ToDictionary(r => r.Name, r => projectBuilds[r.Project]);
            var references = new Dictionary<Name, PackageIL>();
            foreach (var referenceTask in referenceTasks)
            {
                var package = await referenceTask.Value.ConfigureAwait(false);
                if (!(package is null))
                    references.Add(referenceTask.Key, package);
            }

            lock (consoleLock)
            {
                Console.WriteLine([email protected]"Compiling {project.Name} ({project.Path})...");
            }
            var codeFiles = sourcePaths.Select(p => LoadCode(p, sourceDir, project.RootNamespace)).ToList();
            try
            {
                var package = compiler.CompilePackage(project.Name, codeFiles, references.ToFixedDictionary());
                // TODO switch to the async version of the compiler
                //var codeFiles = sourcePaths.Select(p => new CodePath(p)).ToList();
                //var references = project.References.ToDictionary(r => r.Name, r => projectBuilds[r.Project]);
                //var package = await compiler.CompilePackageAsync(project.Name, codeFiles, references);

                if (OutputDiagnostics(project, package.Diagnostics, consoleLock))
                    return package;

                var cacheDir = PrepareCacheDir(project);
                var codePath = EmitCode(project, package, cacheDir);
                var success = CompileCode(project, cacheDir, codePath, consoleLock);

                lock (consoleLock)
                {
                    Console.WriteLine(success
                        ? $"Build SUCCEEDED {project.Name} ({project.Path})"
                        : $"Build FAILED {project.Name} ({project.Path})");
                }

                return package;
            }
            catch (FatalCompilationErrorException ex)
            {
                OutputDiagnostics(project, ex.Diagnostics, consoleLock);
                return null;
            }
        }

19 View Source File : TempDir.cs
License : GNU General Public License v3.0
Project Creator : Alois-xx

public void Dispose()
        {

            if( Name.Length<10)
            {
                throw new InvalidOperationException(String.Format("Directory name seems to be invalid. Do not delete recursively your hard disc.", Name));
            }

            // delete all files in temp directory
 	        foreach(var file in Directory.EnumerateFiles(Name, "*.*", SearchOption.AllDirectories))
            {
                File.Delete(file);
            }

            // and then the directory
            Directory.Delete(Name,true);
        }

19 View Source File : JailDropoff.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

internal static List<JailDropoff> DeserializeDropoffs()
        {
            if (Directory.Exists("Plugins/LSPDFR/Arrest Manager/JailDropoffs"))
            {
                foreach (string file in Directory.EnumerateFiles("Plugins/LSPDFR/Arrest Manager/JailDropoffs", "*.xml", SearchOption.TopDirectoryOnly))
                {
                    try
                    {
                        using (var reader = new StreamReader(file))
                        {
                            XmlSerializer deserializer = new XmlSerializer(typeof(List<JailDropoff>),
                                new XmlRootAttribute("JailDropoffs"));
                            
                            AllJailDropoffs.AddRange((List<JailDropoff>)deserializer.Deserialize(reader));
                        }
                    }
                    catch (Exception e)
                    {
                        Game.LogTrivial(e.ToString());
                        Game.LogTrivial("Arrest Manager - Error parsing XML from " + file);
                    }
                }
            }
            else
            {

            }
            if (AllJailDropoffs.Count == 0)
            {
                Game.DisplayNotification("Arrest Manager couldn't find a valid XML file with Jail Dropoffs in Plugins/LSPDFR/Arrest Manager/JailDropoffs.");
                Game.LogTrivial("Arrest Manager couldn't find a valid XML file with Jail Dropoffs in Plugins/LSPDFR/Arrest Manager/JailDropoffs.");
            }
            return AllJailDropoffs;
        }

19 View Source File : ConformanceTests.cs
License : MIT License
Project Creator : adamant

public static TheoryData<TestCase> GetConformanceTestCases()
        {
            var testCases = new TheoryData<TestCase>();
            var testsDirectory = Path.Combine(SolutionDirectory.Get(), "tests");
            foreach (var fullPath in Directory.EnumerateFiles(testsDirectory, "*.ad", SearchOption.AllDirectories))
            {
                var relativePath = Path.GetRelativePath(testsDirectory, fullPath);
                testCases.Add(new TestCase(fullPath, relativePath));
            }
            return testCases;
        }

19 View Source File : GitRepository.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public IEnumerable<string> FindFiles(string[] searchPatterns, bool recursive = true)
        {
            var files = new List<string>();

            foreach (var searchPattern in searchPatterns)
            {
                var foundFiles = Directory.EnumerateFiles(RepositoryDirectory, searchPattern, new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, RecurseSubdirectories = recursive });
                files.AddRange(foundFiles);
            }

            return files;
        }

19 View Source File : Workspace.cs
License : Apache License 2.0
Project Creator : acblog

public async Task Push(string name = "", bool full = false)
        {
            if (string.IsNullOrEmpty(name))
                name = Option.CurrentRemote;

            Logger.LogInformation($"Push to remote {name}.");

            if (Option.Remotes.TryGetValue(name, out var remote))
            {
                Logger.LogInformation($"Detect remote {remote.Name} ({Enum.GetName(typeof(RemoteType), remote.Type)}).");
                switch (remote.Type)
                {
                    case RemoteType.LocalFS:
                        {
                            await toLocalFS(remote);
                        }
                        break;
                    case RemoteType.RemoteFS:
                        {
                            throw new NotSupportedException("Not support pushing to remote file system, please push to local file system and sync to remote.");
                        }
                    case RemoteType.Api:
                        {
                            await Connect(name);

                            Logger.LogInformation($"Fetch remote posts.");

                            await Remote.SetOptions(await Local.GetOptions());

                            await SyncRecordRepository(Local.PostService, Remote.PostService, full);

                            await SyncRecordRepository(Local.PageService, Remote.PageService, full);

                            await SyncRecordRepository(Local.LayoutService, Remote.LayoutService, full);
                        }
                        break;
                    case RemoteType.Git:
                        {
                            await Connect(name);

                            string tempDist = Path.Join(Environment.CurrentDirectory, "temp/dist");

                            Logger.LogInformation("Generate data.");

                            await toLocalFS(new RemoteOption
                            {
                                Uri = tempDist,
                                Type = RemoteType.LocalFS,
                                Name = remote.Name
                            });

                            FSExtensions.CopyDirectory(tempDist, GitTempFolder);

                            Logger.LogInformation("Load git config.");

                            string userName = Option.Properties[$"remote.{remote.Name}.git.username"],
                                preplacedword = Option.Properties[$"remote.{remote.Name}.git.preplacedword"];

                            {
                                if (string.IsNullOrEmpty(userName))
                                    userName = ConsoleExtensions.Input("Input username: ");
                                if (string.IsNullOrEmpty(preplacedword))
                                    preplacedword = ConsoleExtensions.InputPreplacedword("Input preplacedword: ");
                            }

                            using (var repo = new Repository(GitTempFolder))
                            {
                                Logger.LogInformation("Commit to git.");

                                LibGit2Sharp.Commands.Stage(repo, "*");

                                var signature = new LibGit2Sharp.Signature(
                                        new Idenreplacedy("AcBlog.Tools.Sdk", "[email protected]"), DateTimeOffset.Now);
                                repo.Commit(DateTimeOffset.Now.ToString(), signature, signature, new CommitOptions
                                {
                                    AllowEmptyCommit = true
                                });

                                Logger.LogInformation($"Push to {repo.Head.RemoteName}.");

                                PushOptions options = new PushOptions
                                {
                                    CredentialsProvider = new CredentialsHandler(
                                    (url, usernameFromUrl, types) =>
                                        new UsernamePreplacedwordCredentials()
                                        {
                                            Username = string.IsNullOrEmpty(userName) ? usernameFromUrl : userName,
                                            Preplacedword = preplacedword
                                        })
                                };
                                repo.Network.Push(repo.Head, options);
                            }
                        }
                        break;
                }
            }
            else
            {
                throw new Exception("No remote");
            }

            async Task toLocalFS(RemoteOption remote)
            {
                FSBuilder fsBuilder = new FSBuilder(remote.Uri);
                fsBuilder.EnsureDirectoryEmpty();

                List<Post> posts = new List<Post>();
                await foreach (var item in Local.PostService.GetAllItems().IgnoreNull())
                {
                    Logger.LogInformation($"Loaded Post {item.Id}: {item.replacedle}");
                    posts.Add(item);
                }

                List<Layout> layouts = new List<Layout>();
                await foreach (var item in Local.LayoutService.GetAllItems().IgnoreNull())
                {
                    Logger.LogInformation($"Loaded Layout {item.Id}");
                    layouts.Add(item);
                }

                List<Page> pages = new List<Page>();
                await foreach (var item in Local.PageService.GetAllItems().IgnoreNull())
                {
                    Logger.LogInformation($"Loaded Page {item.Id}: {item.replacedle}");
                    pages.Add(item);
                }

                var baseAddress = Option.Properties[$"remote.{remote.Name}.generator.baseAddress"];

                List<Data.Models.File> files = new List<Data.Models.File>();
                {
                    string path = Path.Join(Environment.CurrentDirectory, replacedetsPath);
                    if (Directory.Exists(path))
                    {
                        foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories))
                        {
                            var id = Path.GetRelativePath(Environment.CurrentDirectory, file).Replace('\\', '/');
                            Data.Models.File f = new Data.Models.File
                            {
                                Id = id,
                                Uri = string.IsNullOrWhiteSpace(baseAddress) ? $"/{id}" : $"{baseAddress.TrimEnd('/')}/{id}"
                            };
                            files.Add(f);
                        }
                    }
                }

                Logger.LogInformation("Build data.");
                {
                    BlogOptions options = await Local.GetOptions();
                    BlogBuilder builder = new BlogBuilder(options, Path.Join(remote.Uri));
                    await builder.Build();
                    await builder.BuildPosts(posts);
                    await builder.BuildLayouts(layouts);
                    await builder.BuildPages(pages);
                    await builder.BuildFiles(files);
                }

                {
                    if (!string.IsNullOrEmpty(baseAddress))
                    {
                        Logger.LogInformation("Build sitemap.");
                        var sub = fsBuilder.CreateSubDirectoryBuilder("Site");
                        {
                            var siteMapBuilder = await Local.BuildSitemap(baseAddress);
                            await using var st = sub.GetFileRewriteStream("sitemap.xml");
                            await using var writer = XmlWriter.Create(st, new XmlWriterSettings { Async = true });
                            siteMapBuilder.Build().WriteTo(writer);
                        }
                        Logger.LogInformation("Build feed.");
                        {
                            var feed = await Local.BuildSyndication(baseAddress);
                            await using (var st = sub.GetFileRewriteStream("atom.xml"))
                            {
                                await using var writer = XmlWriter.Create(st, new XmlWriterSettings { Async = true });
                                feed.GetAtom10Formatter().WriteTo(writer);
                            }
                            await using (var st = sub.GetFileRewriteStream("rss.xml"))
                            {
                                await using var writer = XmlWriter.Create(st, new XmlWriterSettings { Async = true });
                                feed.GetRss20Formatter().WriteTo(writer);
                            }
                        }
                    }
                }
                {
                    string replacedetsPath = Path.Join(Environment.CurrentDirectory, replacedetsPath);
                    if (Directory.Exists(replacedetsPath))
                    {
                        Logger.LogInformation("Copy replacedets.");
                        FSExtensions.CopyDirectory(replacedetsPath, Path.Join(remote.Uri, replacedetsPath));
                    }
                }
            }
        }

19 View Source File : OpenVPNSession.cs
License : GNU General Public License v3.0
Project Creator : Amebis

protected override void DoRun()
        {
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
            try
            {
                try
                {
                    // Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
                    var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
                    mgmtServer.Start();
                    try
                    {
                        try
                        {
                            // Purge stale log files.
                            var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
                            foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
                            {
                                SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
                                if (File.GetLastWriteTimeUtc(f) <= timestamp)
                                {
                                    try { File.Delete(LogPath); }
                                    catch { }
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception) { /* Failure to remove stale log files is not fatal. */ }

                        try
                        {
                            // Save OpenVPN configuration file.
                            using (var fs = new FileStream(
                                ConfigurationPath,
                                FileMode.Create,
                                FileAccess.Write,
                                FileShare.Read,
                                1048576,
                                FileOptions.SequentialScan))
                            using (var sw = new StreamWriter(fs))
                            {
                                // Save profile's configuration to file.

                                if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
                                {
                                    // Remove options on the OpenVPNRemoveOptions list on the fly.
                                    using (var sr = new StringReader(ProfileConfig))
                                    {
                                        string inlineTerm = null;
                                        bool inlineRemove = false;
                                        for (; ; )
                                        {
                                            var line = sr.ReadLine();
                                            if (line == null)
                                                break;

                                            var trimmedLine = line.Trim();
                                            if (!string.IsNullOrEmpty(trimmedLine))
                                            {
                                                // Not an empty line.
                                                if (inlineTerm == null)
                                                {
                                                    // Not inside an inline option block = Regular parsing mode.
                                                    if (!trimmedLine.StartsWith("#") &&
                                                        !trimmedLine.StartsWith(";"))
                                                    {
                                                        // Not a comment.
                                                        var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
                                                        if (option.Count > 0)
                                                        {
                                                            if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
                                                            {
                                                                // Start of an inline option.
                                                                var o = option[0].Substring(1, option[0].Length - 2);
                                                                inlineTerm = "</" + o + ">";
                                                                inlineRemove = openVPNRemoveOptions.Contains(o);
                                                                if (inlineRemove)
                                                                {
                                                                    sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                    line = "# " + line;
                                                                }
                                                            }
                                                            else if (openVPNRemoveOptions.Contains(option[0]))
                                                            {
                                                                sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                line = "# " + line;
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    // Inside an inline option block.
                                                    if (inlineRemove)
                                                    {
                                                        // Remove the inline option content.
                                                        line = "# " + line;
                                                    }

                                                    if (trimmedLine == inlineTerm)
                                                    {
                                                        // Inline option terminator found. Returning to regular parsing mode.
                                                        inlineTerm = null;
                                                    }
                                                }
                                            }

                                            sw.WriteLine(line);
                                        }
                                    }
                                }
                                else
                                    sw.Write(ProfileConfig);

                                // Append eduVPN Client specific configuration directives.
                                sw.WriteLine();
                                sw.WriteLine();
                                sw.WriteLine("# eduVPN Client for Windows");

                                // Introduce ourself (to OpenVPN server).
                                var replacedembly = replacedembly.GetExecutingreplacedembly();
                                var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
                                var replacedemblyVersion = replacedembly?.GetName()?.Version;
                                sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));

                                // Configure log file (relative to WorkingFolder).
                                sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));

                                // Configure interaction between us and openvpn.exe.
                                sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
                                sw.WriteLine("management-client");
                                sw.WriteLine("management-hold");
                                sw.WriteLine("management-query-preplacedwords");
                                sw.WriteLine("management-query-remote");

                                // Configure client certificate.
                                sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
                                sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));

                                // Ask when username/preplacedword is denied.
                                sw.WriteLine("auth-retry interact");
                                sw.WriteLine("auth-nocache");

                                // Set Wintun interface to be used.
                                sw.Write("windows-driver wintun\n");
                                sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");

#if DEBUG
                                // Renegotiate data channel every 5 minutes in debug versions.
                                sw.WriteLine("reneg-sec 300");
#endif

                                if (Environment.OSVersion.Version < new Version(6, 2))
                                {
                                    // Windows 7 is using tiny 8kB send/receive socket buffers by default.
                                    // Increase to 64kB which is default from Windows 8 on.
                                    sw.WriteLine("sndbuf 65536");
                                    sw.WriteLine("rcvbuf 65536");
                                }

                                var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
                                if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
                                {
                                    sw.WriteLine();
                                    sw.WriteLine();
                                    sw.WriteLine("# Added by OpenVPNAddOptions setting:");
                                    sw.WriteLine(openVPNAddOptions);
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }

                        bool retry;
                        do
                        {
                            retry = false;

                            // Connect to OpenVPN Interactive Service to launch the openvpn.exe.
                            using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
                            {
                                var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
                                try
                                {
                                    openvpnInteractiveServiceConnection.Connect(
                                        string.Format("openvpn{0}\\service", InstanceName),
                                        WorkingFolder,
                                        new string[] { "--config", ConnectionId + ".conf", },
                                        mgmtPreplacedword + "\n",
                                        3000,
                                        SessionAndWindowInProgress.Token);
                                }
                                catch (OperationCanceledException) { throw; }
                                catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }

                                try
                                {
                                    // Wait and accept the openvpn.exe on our management interface (--management-client parameter).
                                    var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
                                    try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
                                    catch (AggregateException ex) { throw ex.InnerException; }
                                    var mgmtClient = mgmtClientTask.Result;
                                    try
                                    {
                                        // Start the management session.
                                        ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);

                                        // Initialize session and release openvpn.exe to get started.
                                        ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
                                        ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);

                                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
                                        try
                                        {
                                            // Wait for the session to end gracefully.
                                            ManagementSession.Monitor.Join();
                                            if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
                                            {
                                                // Session reported an error. Retry.
                                                retry = true;
                                            }
                                        }
                                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
                                    }
                                    finally { mgmtClient.Close(); }
                                }
                                finally
                                {
                                    Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                                        () =>
                                        {
                                            // Cleanup status properties.
                                            State = SessionStatusType.Disconnecting;
                                            StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
                                            TunnelAddress = null;
                                            IPv6TunnelAddress = null;
                                            ConnectedAt = null;
                                            BytesIn = null;
                                            BytesOut = null;
                                        }));

                                    // Wait for openvpn.exe to finish. Maximum 30s.
                                    try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
                                    catch (ArgumentException) { }
                                }
                            }
                        } while (retry);
                    }
                    finally
                    {
                        mgmtServer.Stop();
                    }
                }
                finally
                {
                    // Delete profile configuration file. If possible.
                    try { File.Delete(ConfigurationPath); }
                    catch { }
                }
            }
            finally
            {
                Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                    () =>
                    {
                        // Cleanup status properties.
                        State = SessionStatusType.Disconnected;
                        StateDescription = "";

                        Wizard.TaskCount--;
                    }));
                PropertyUpdater.Stop();
            }
        }

19 View Source File : SmallFactorizationTest.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

private void RecursiveDelete(string path)
		{
			IEnumerable<string> files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories);
			foreach (string file in files)
			{
				File.Delete(file);
			}

			IEnumerable<string> directories = Directory.EnumerateDirectories(path, "*", SearchOption.AllDirectories);
			foreach (string directory in directories)
			{
				RecursiveDelete(directory);
			}

			Directory.Delete(path);
		}

19 View Source File : CodeStructureParser.cs
License : MIT License
Project Creator : AndresTraks

public static RootFolderDefinition Parse(string rootFolderPath)
        {
            var rootFolder = new RootFolderDefinition(rootFolderPath);

            var headerFiles = Directory.EnumerateFiles(rootFolderPath, "*.h", SearchOption.AllDirectories);
            foreach (string headerPath in headerFiles)
            {
                var path = headerPath.Replace('\\', '/');
                path = path.Substring(rootFolderPath.Length + 1);

                var headerFolder = CreateFoldersOnPath(path, rootFolder);

                string fileName = Path.GetFileName(path);
                headerFolder.AddChild(new HeaderDefinition(fileName));
            }

            return rootFolder;
        }

19 View Source File : IrdTests.cs
License : MIT License
Project Creator : 13xforever

[Test, Explicit("Requires custom data")]
        public async Task TocSizeTest()
        {
            var path = @"E:\FakeCDs\PS3 Games\ird";
            var result = new List<(string filename, long size)>();
            foreach (var f in Directory.EnumerateFiles(path, "*.ird", SearchOption.TopDirectoryOnly))
            {
                var bytes = await File.ReadAllBytesAsync(f).ConfigureAwait(false);
                var ird = IrdParser.Parse(bytes);
                using (var header = GetDecompressHeader(ird))
                    result.Add((Path.GetFileName(f), header.Length));
            }
            replacedert.That(result.Count, Is.GreaterThan(0));

            var groupedStats = (from t in result
                    group t by t.size into g
                    select new {size = g.Key, count = g.Count()}
                ).OrderByDescending(i => i.count)
                .ThenByDescending(i => i.size)
                .ToList();

            var largest = groupedStats.Max(i => i.size);
            var largesreplacedem = result.First(i => i.size == largest);
            Console.WriteLine($"Largest TOC: {largesreplacedem.filename} ({largest.replacedtorageUnit()})");

            foreach (var s in groupedStats)
                Console.WriteLine($"{s.count} items of size {s.size}");

            replacedert.That(groupedStats.Count, Is.EqualTo(1));
        }

19 View Source File : IconLoader.cs
License : MIT License
Project Creator : AnnoDesigner

public Dictionary<string, IconImage> Load(string pathToIconFolder, IconMappingPresets iconNameMapping)
        {
            Dictionary<string, IconImage> result = null;

            try
            {
                result = new Dictionary<string, IconImage>();

                foreach (var path in Directory.EnumerateFiles(pathToIconFolder, CoreConstants.IconFolderFilter))
                {
                    var filenameWithoutExt = Path.GetFileNameWithoutExtension(path);
                    if (string.IsNullOrWhiteSpace(filenameWithoutExt))
                    {
                        continue;
                    }

                    var filenameWithExt = Path.GetFileName(path);

                    // try mapping to the icon translations
                    Dictionary<string, string> localizations = null;
                    if (iconNameMapping?.IconNameMappings != null)
                    {
                        var map = iconNameMapping.IconNameMappings.Find(x => string.Equals(x.IconFilename, filenameWithExt, StringComparison.OrdinalIgnoreCase));
                        if (map != null)
                        {
                            localizations = map.Localizations.Dict;
                        }
                    }

                    // add the current icon
                    result.Add(filenameWithoutExt, new IconImage(filenameWithoutExt, localizations, path));
                }

                // sort icons by their DisplayName
                result = result.OrderBy(x => x.Value.DisplayName).ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);//make sure ContainsKey is caseInSensitive
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error loading the icons.");
                throw;
            }

            return result;
        }

19 View Source File : Platform.Posix.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string[] EnumerateLibLdConf(string fileName)
			{
				if (!File.Exists(fileName)) return null;

				var libLoadConf = new List<string>();
				using (var fileReader = new StreamReader(fileName))
				{
					while (!fileReader.EndOfStream)
					{
						string line = fileReader.ReadLine().TrimStart(new char[] { ' ' });

						// Comments
						if (line.StartsWith("#", StringComparison.OrdinalIgnoreCase)) continue;
						int commentI;
						if (-1 < (commentI = line.IndexOf("#")))
						{
							// remove Comments
							line = line.Substring(0, commentI);
						}

						if (string.IsNullOrWhiteSpace(line.Trim())) continue;

						// Include /etc/ld.so.conf.d/*.conf, say enumerate files
						if (line.StartsWith("include ", StringComparison.OrdinalIgnoreCase))
						{
							string folder = null;
							string filesPattern = line.Substring("include ".Length);
							int filesPatternI;
							if (-1 == (filesPatternI = filesPattern.IndexOf('*')))
							{
								filesPatternI = filesPattern.Length;
							}
							if (-1 < (filesPatternI = filesPattern.LastIndexOf('/', filesPatternI)))
							{
								folder = filesPattern.Substring(0, filesPatternI + 1);
								filesPattern = filesPattern.Substring(filesPatternI + 1);
							}

							if (folder == null || !Directory.Exists(folder)) continue;

							string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();

							foreach (string file in files)
							{
								string[] _libLoadConf = EnumerateLibLdConf(file);
								if (_libLoadConf != null) libLoadConf.AddRange(_libLoadConf);
							}

							continue;
						}

						// Folder
						string path = EnsureNotEndingSlash(line);
						if (path != null && Directory.Exists(path)) libLoadConf.Add(path);
					}
				}

				return libLoadConf.ToArray();
			}

19 View Source File : PluginCore.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void GarbageTTSCache()
        {
            var cacheFolder = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                @"anoyetta\ACT\tts cache");

            if (!Directory.Exists(cacheFolder))
            {
                return;
            }

            Directory.EnumerateFiles(
                cacheFolder,
                "*.*",
                SearchOption.TopDirectoryOnly).Walk((file) =>
                {
                    var timestamp = File.GetLastAccessTime(file);
                    if ((DateTime.Now - timestamp).TotalDays > 30)
                    {
                        File.Delete(file);
                    }
                });

            Directory.EnumerateFiles(
                cacheFolder,
                "*本日は晴天なり*",
                SearchOption.TopDirectoryOnly).Walk((file) =>
                {
                    File.Delete(file);
                });
        }

19 View Source File : ProjectFolder.cs
License : MIT License
Project Creator : action-bi-toolkit

public IEnumerable<IProjectFile> GetFiles(string searchPattern, SearchOption searchOption) =>
            this.Exists()
            ? Directory.EnumerateFiles(this.BasePath, searchPattern, searchOption)
                .Select(path => new ProjectFile(this._root, path))
            : new IProjectFile[0];

19 View Source File : ColladaLoader.Utilities.cs
License : MIT License
Project Creator : ansel86castro

private HashSet<string> LoadFilenames()
        {
            var dir = string.IsNullOrEmpty(_directory) ? "." : _directory;
            var set = new HashSet<string>();

            foreach (var file in Directory.EnumerateFiles(dir))
            {
                set.Add(file);
            }
            return set;
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ahopper

private void ExportFromSVG(string replacedle, string path)
        {
            using (var file = File.CreateText($"..\\..\\..\\Avalonia.IconPacks\\Icons\\{replacedle}.xaml"))
            {
                file.WriteLine("<Styles xmlns=\"https://github.com/avaloniaui\"");
                file.WriteLine("    xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" >");
                file.WriteLine("    <Style>");
                file.WriteLine("        <Style.Resources>");


                foreach (var svgpath in Directory.EnumerateFiles(path, "*.svg", SearchOption.AllDirectories))
                {
                    try
                    {
                        XmlDoreplacedent drawingDoc = new XmlDoreplacedent();
                        using (XmlTextReader tr = new XmlTextReader(svgpath))
                        {
                            tr.Namespaces = false;
                            drawingDoc.Load(tr);
                        }
                        var name = Path.GetFileNameWithoutExtension(svgpath);
                        var dgChildren = drawingDoc.DoreplacedentElement.GetElementsByTagName("path");
                        if (dgChildren.Count == 1)
                        {
                            file.WriteLine($"            <GeometryDrawing x:Key=\"{replacedle}.{name}\" Brush=\"{dgChildren[0].Attributes["fill"].Value}\" Geometry=\"{dgChildren[0].Attributes["d"].Value}\"/>");
                        }
                        else
                        {
                            file.WriteLine($"            <DrawingGroup x:Key=\"{replacedle}.{name}\" >");
                            foreach (XmlElement dp in dgChildren)
                            {
                                file.WriteLine($"              <GeometryDrawing Brush=\"{dp.Attributes["fill"].Value}\" Geometry=\"{dp.Attributes["d"].Value}\"/>");
                            }
                            file.WriteLine($"            </DrawingGroup>");
                        }
                    }
                    catch (Exception e)
                    {

                    }
                }
                file.WriteLine("        </Style.Resources>");
                file.WriteLine("    </Style>");
                file.WriteLine("</Styles>");
            }
 
        }

19 View Source File : helpers.cs
License : Apache License 2.0
Project Creator : AntonioDePau

public static IEnumerable<string> GetAllFiles(string folder)
        {
			if(!Directory.Exists(folder)) return Enumerable.Empty<string>();
            return Directory.EnumerateFiles(folder, "*.*", SearchOption.AllDirectories)
                            .Select(x => x.Replace($"{folder}\\", "")
                            .Replace(@"\", "/"));
        }

19 View Source File : IFileSystem.cs
License : MIT License
Project Creator : 0x1000000

public IEnumerable<string> EnumerateFiles(string path, string pattern, SearchOption searchOption)
        {
            return Directory.EnumerateFiles(path, pattern, searchOption);
        }

19 View Source File : AsyncParsingTests.cs
License : MIT License
Project Creator : Aptiv-WLL

[TestMethod()]
        [TestProperty("Category", "Load DBC")]
        public async Task DBCFileTest0()
        {
            foreach (var dbc in Directory.EnumerateFiles(TestToken.path, "*.dbc", SearchOption.AllDirectories))
            {
                dbf = new DBCFile(dbc, false);
                await dbf.CreateLibraryDBCAsync();
                Console.WriteLine(dbc);
            }
        }

19 View Source File : TestHelpers.cs
License : MIT License
Project Creator : airbreather

public static IEnumerable<object[]> GetTestCsvFilesWithChunkLengths(params string[] pathParts) =>
            from filePath in Directory.EnumerateFiles(Path.Combine(TestCsvFilesFolderPath, Path.Combine(pathParts)), "*.csv", SearchOption.AllDirectories)
            let relativePath = Path.GetRelativePath(TestCsvFilesFolderPath, filePath)
            from chunkLength in TestChunkLengths
            select new object[] { relativePath, chunkLength };

19 View Source File : ProjectRootFolder.cs
License : MIT License
Project Creator : action-bi-toolkit

public void Dispose()
        {
            // Do not delete anything if an unhandled error has occurred
            if (!_committed) return;

            if (_filesWritten.Count == 0)
            {
                if (Directory.Exists(BasePath))
                {
                    Directory.Delete(BasePath, recursive: true);
                    Log.Information("No files written. Removed base folder: {Path}", BasePath);
                }

                return;
            }

            // Remove any existing files that have not been updated
            foreach (var path in Directory.GetFiles(BasePath, "*.*", SearchOption.AllDirectories))
            {
                if (!_filesWritten.Contains(path))
                {
                    File.Delete(path);
                    Log.Information("Removed file: {Path}", path);
                }
            }

            // Remove empty dirs:
            foreach (var dir in Directory.GetDirectories(BasePath, "*", SearchOption.AllDirectories).ToArray())
            {
                if (Directory.Exists(dir) && Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories).FirstOrDefault() == null)
                {
                    Directory.Delete(dir, recursive: true); // Could be root of a series of empty folders
                    Log.Information("Removed empty directory: {Path}", dir);
                }
            }

            // TODO Check if nested empty dirs need to be removed explicitly
            // ./ROOT
            // ./ROOT/dir1
            // ./ROOT/dir1/file.txt
            // ./ROOT/dir1/empty/ ***
        }

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade

public void RestoreBackup(string root, string origRoot) {
            Log($"[RestoreBackup] Restoring from {origRoot} to {root}");
            foreach (string origPath in Directory.EnumerateFiles(origRoot, "*", SearchOption.AllDirectories)) {
                Directory.CreateDirectory(Path.GetDirectoryName(root + origPath.Substring(origRoot.Length)));
                File.Copy(origPath, root + origPath.Substring(origRoot.Length), true);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000

public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
        {
            List<NodeModel> result = new List<NodeModel>();
				
            var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);

            files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));

            var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
            var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);

            foreach (var tree in trees)
            {
                var semantic = cSharpCompilation.GetSemanticModel(tree);

                foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
                {
                    var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
                    
                    var isSuitable = clreplacedSymbol != null 
                                 && !clreplacedSymbol.IsAbstract 
                                 && clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
                                 && IsExpr(clreplacedSymbol) 
                                 && clreplacedSymbol.Name.StartsWith("Expr");
                        
                    if (!isSuitable)
                    {
                        continue;
                    }

                    var properties = GetProperties(clreplacedSymbol);

                    var subNodes = new List<SubNodeModel>();
                    var modelProps = new List<SubNodeModel>();

                    foreach (var constructor in clreplacedSymbol.Constructors)
                    {
                        foreach (var parameter in constructor.Parameters)
                        {
                            INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;

                            var correspondingProperty = properties.FirstOrDefault(prop =>
                                string.Equals(prop.Name,
                                    parameter.Name,
                                    StringComparison.CurrentCultureIgnoreCase));

                            if (correspondingProperty == null)
                            {
                                throw new Exception(
                                    $"Could not find a property for the constructor arg: '{parameter.Name}'");
                            }

                            var ta = replacedyzeSymbol(ref pType);

                            var subNodeModel = new SubNodeModel(correspondingProperty.Name,
                                parameter.Name,
                                pType.Name,
                                ta.ListName,
                                ta.IsNullable,
                                ta.HostTypeName);
                            if (ta.Expr)
                            {
                                subNodes.Add(subNodeModel);
                            }
                            else
                            {
                                modelProps.Add(subNodeModel);
                            }

                        }
                    }

                    result.Add(new NodeModel(clreplacedSymbol.Name,
                        modelProps.Count == 0 && subNodes.Count == 0,
                        subNodes,
                        modelProps));
                }
            }

            result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));

            return result;

            bool IsExpr(INamedTypeSymbol symbol)
            {
                if (symbol.Name == "IExpr")
                {
                    return true;
                }
                while (symbol != null)
                {
                    if (symbol.Interfaces.Any(HasA))
                    {
                        return true;
                    }
                    symbol = symbol.BaseType;
                }

                return false;


                bool HasA(INamedTypeSymbol iSym)
                {
                    if (iSym.Name == "IExpr")
                    {
                        return true;
                    }

                    return IsExpr(iSym);
                }
            }

            List<ISymbol> GetProperties(INamedTypeSymbol symbol)
            {
                List<ISymbol> result = new List<ISymbol>();
                while (symbol != null)
                {
                    result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
                    symbol = symbol.BaseType;
                }

                return result;
            }

            Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
            {
                string listName = null;
                string hostType = null;
                if (typeSymbol.ContainingType != null)
                {
                    var host = typeSymbol.ContainingType;
                    hostType = host.Name;
                }

                var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;

                if (nullable && typeSymbol.Name == "Nullable")
                {
                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                if (typeSymbol.IsGenericType)
                {
                    if (typeSymbol.Name.Contains("List"))
                    {
                        listName = typeSymbol.Name;
                    }

                    if (typeSymbol.Name == "Nullable")
                    {
                        nullable = true;
                    }

                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
            }
        }

19 View Source File : UserManager.cs
License : Apache License 2.0
Project Creator : ac87

public void SignOut()
        {
            if (_credential != null)
            {
                if (_tokenRefreshTimer != null)
                    _tokenRefreshTimer.Stop();

                _credential.RevokeTokenAsync(CancellationToken.None).Wait();

                foreach (string file in Directory.EnumerateFiles(Utils.GetDataStoreFolder()))
                {
                    if (file.Contains("-user"))
                    {
                        File.Delete(file);
                        return;
                    }
                }
            }

            _credential = null;
        }

19 View Source File : ConformanceTests.cs
License : MIT License
Project Creator : adamant

private PackageIL CompileStdLib(AdamantCompiler compiler)
        {
            try
            {
                var sourceDir = Path.Combine(SolutionDirectory.Get(), @"stdlib\src");
                var sourcePaths =
                    Directory.EnumerateFiles(sourceDir, "*.ad", SearchOption.AllDirectories);
                var rootNamespace = FixedList<string>.Empty;
                var codeFiles = sourcePaths.Select(p => LoadCode(p, sourceDir, rootNamespace))
                    .ToList();
                return compiler.CompilePackage("adamant.stdlib", codeFiles,
                    FixedDictionary<Name, PackageIL>.Empty);
            }
            catch (FatalCompilationErrorException ex)
            {
                testOutput.WriteLine("Std Lib Compiler Errors:");
                foreach (var diagnostic in ex.Diagnostics)
                {
                    testOutput.WriteLine(
                        $"{diagnostic.File.Reference}:{diagnostic.StartPosition.Line}:{diagnostic.StartPosition.Column} {diagnostic.Level} {diagnostic.ErrorCode}");
                    testOutput.WriteLine(diagnostic.Message);
                }
                replacedert.True(false, "Compilation errors in standard library");
                throw new UnreachableCodeException();
            }
        }

19 View Source File : Offence.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

internal static List<Offence> DeserializeOffences()
        {
            List<Offence> AllOffences = new List<Offence>();
            if (Directory.Exists("Plugins/LSPDFR/LSPDFR+/Offences"))
            {
                foreach (string file in Directory.EnumerateFiles("Plugins/LSPDFR/LSPDFR+/Offences", "*.xml", SearchOption.TopDirectoryOnly))
                {
                    try
                    {
                        using (var reader = new StreamReader(file))
                        {
                            XmlSerializer deserializer = new XmlSerializer(typeof(List<Offence>),
                                new XmlRootAttribute("Offences"));
                            AllOffences.AddRange((List<Offence>)deserializer.Deserialize(reader));
                        }
                    }
                    catch (Exception e)
                    {
                        Game.LogTrivial(e.ToString());
                        Game.LogTrivial("LSPDFR+ - Error parsing XML from " + file);
                    }
                }
            }
            else
            {
                
            }
            if (AllOffences.Count == 0)
            {
                AllOffences.Add(new Offence());
                Game.DisplayNotification("~r~~h~LSPDFR+ couldn't find a valid XML file with offences in Plugins/LSPDFR/LSPDFR+/Offences. Setting just the default offence.");
            }
            CategorizedTrafficOffences = AllOffences.GroupBy(x => x.offenceCategory).ToDictionary(x => x.Key, x => x.ToList());
            return AllOffences;
        }

See More Examples