System.IO.Directory.EnumerateFiles(string)

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

343 Examples 7

19 Source : Program.cs
with MIT License
from 0x1000000

private static async Task RunGenModelsOptions(GenModelsOptions options)
        {
            ILogger logger = new DefaultLogger(Console.Out, options.Verbosity);

            logger.LogMinimal("Model clreplacedes generation is running...");

            string inDirectory = EnsureDirectory(options.InputDir, logger, "Input", false);
            string outDirectory = EnsureDirectory(options.OutputDir, logger, "Output", true);

            var replacedysis = ExistingCodeExplorer
                .EnumerateTableDescriptorsModelAttributes(inDirectory, DefaultFileSystem.Instance)
                .ParseAttribute(options.NullRefTypes)
                .Createreplacedysis();

            if (replacedysis.Count < 1)
            {
                logger.LogNormal("No model attributes detected in the input directory.");
            }
            else
            {
                logger.LogNormal($"Found {replacedysis.Count} models in the input directory.");
            }

            if (logger.IsDetailed)
            {
                foreach (var model in replacedysis)
                {
                    logger.LogDetailed(model.Name);
                    foreach (var property in model.Properties)
                    {
                        logger.LogDetailed(
                            $" -{property.Type} {property.Name}");
                        foreach (var col in property.Column)
                        {
                            logger.LogDetailed(
                                $"   ={(property.CastType != null ? $"({property.CastType})" : null)}{col.TableRef.TableTypeName}.{col.ColumnName}");
                        }
                    }
                }
            }

            logger.LogNormal("Code generation...");

            foreach (var meta in replacedysis)
            {
                string path = Path.Combine(outDirectory, $"{meta.Name}.cs");
                if (logger.IsDetailed) logger.LogDetailed(path);
                await File.WriteAllTextAsync(path, ModelClreplacedGenerator.Generate(meta, options.Namespace, path, options.RwClreplacedes, DefaultFileSystem.Instance, out var existing).ToFullString());
                if (logger.IsDetailed) logger.LogDetailed(existing ? "Existing file updated." : "New file created.");
            }

            if (options.CleanOutput)
            {
                var modelFiles = replacedysis.Select(meta => $"{meta.Name}.cs").ToHashSet(StringComparer.InvariantCultureIgnoreCase);

                var toRemove = Directory.EnumerateFiles(outDirectory).Where(p=> !modelFiles.Contains(Path.GetFileName(p))).ToList();

                foreach (var delPath in toRemove)
                {
                    File.Delete(delPath);
                    if(logger.IsNormalOrHigher) logger.LogNormal($"File {Path.GetFileName(delPath)} has been removed since it does not contain any model clreplaced");
                }

            }


            logger.LogMinimal("Model clreplacedes generation successfully completed!");
        }

19 Source : DateAndSizeRollingFileAppender.cs
with MIT License
from Abc-Arbitrage

private int FindLastRollingFileNumber(string directory)
        {
            var fileNumber = 0;
            var root = FilenameRoot + ".";
            var extension = FilenameExtension.Length == 0 ? "" : "." + FilenameExtension;
            foreach (var filename in Directory.EnumerateFiles(directory).Select(f => f.ToUpper()))
            {
                if (filename.StartsWith(root, StringComparison.OrdinalIgnoreCase) && filename.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
                {
                    var rootLength = root.Length;
                    var extensionLength = extension.Length;
                    if (filename.Length - rootLength - extensionLength > 0 && int.TryParse(filename.Substring(rootLength, filename.Length - rootLength - extensionLength), out var tempNumber))
                        fileNumber = Math.Max(fileNumber, tempNumber);
                }
            }

            return fileNumber;
        }

19 Source : Utils.cs
with Apache License 2.0
from ac87

public static string GetTokenFile()
        {
            // Can't find a nicer way in the OAuth2 Lib to see if we've ever authorised, so look for the datastore file 
            return Directory.EnumerateFiles(GetDataStoreFolder()).FirstOrDefault(file => file.Contains($"-{Const.User}"));
        }

19 Source : BasicFileCacheManager.cs
with Apache License 2.0
from acarteas

public override IEnumerable<string> GetKeys(string regionName = null)
        {
            string region = "";
            if (string.IsNullOrEmpty(regionName) == false)
            {
                region = regionName;
            }
            string directory = Path.Combine(CacheDir, CacheSubFolder, region);
            if (Directory.Exists(directory))
            {
                foreach (string file in Directory.EnumerateFiles(directory))
                {
                    yield return Path.GetFileNameWithoutExtension(file);
                }
            }
        }

19 Source : TempFileUtils.cs
with GNU General Public License v3.0
from alexdillon

public static void InitializeTempStorage()
        {
            if (Directory.Exists(GroupMeDesktopClientTempFolder))
            {
                foreach (var file in Directory.EnumerateFiles(GroupMeDesktopClientTempFolder))
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            Directory.CreateDirectory(GroupMeDesktopClientTempFolder);
        }

19 Source : MainWindowViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void ClearTempFiles()
        {
            var tempFolder = Path.Combine(Path.GetTempPath(), "GroupMeDesktopClientAvalonia");
            if (Directory.Exists(tempFolder))
            {
                foreach (var file in Directory.EnumerateFiles(tempFolder))
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            Directory.CreateDirectory(tempFolder);
        }

19 Source : FileStorageService.cs
with MIT License
from AndrewBrianHall

public async Task<IEnumerable<UploadedImage>> GetImagesAsync()
        {
            var imageList = new List<UploadedImage>();
            var files = await Task.Run(() => Directory.EnumerateFiles(ImageFolder));

            foreach(var file in files)
            {
                var image = new UploadedImage
                {
                    ImagePath = ImageFolderUri + "/" + Path.GetFileName(file)
                };

                imageList.Add(image);
            }

            return imageList;
        }

19 Source : FindUngroupedViewModel.cs
with MIT License
from andydandy74

public void OnBatchFixUngroupedClicked(string directoryPath)
		{
			// Read directory contents
			var graphs = System.IO.Directory.EnumerateFiles(directoryPath);
			int graphCount = 0;
			foreach (var graph in graphs)
			{
				var ext = System.IO.Path.GetExtension(graph);
				if (ext == ".dyn")
				{
					viewModel.OpenCommand.Execute(graph);
					viewModel.CurrentSpaceViewModel.RunSettingsViewModel.Model.RunType = RunType.Manual;
					FixUngrouped();
					viewModel.SaveAsCommand.Execute(graph);
					viewModel.CloseHomeWorkspaceCommand.Execute(null);
					graphCount += 1;
				}
			}
			batchProcessResults = "Fixed all missing groupings in " + graphCount.ToString() + " graphs...";
			RaisePropertyChanged(nameof(CurrentUngrouped));
		}

19 Source : PlayerInputsViewModel.cs
with MIT License
from andydandy74

public void OnBatchResetInputsClicked(string directoryPath)
		{
			// Read directory contents
			var graphs = System.IO.Directory.EnumerateFiles(directoryPath);
			int graphCount = 0;
			foreach (var graph in graphs)
			{
				var ext = System.IO.Path.GetExtension(graph);
				if (ext == ".dyn")
				{
					viewModel.OpenCommand.Execute(graph);
					viewModel.CurrentSpaceViewModel.RunSettingsViewModel.Model.RunType = RunType.Manual;
					ResetAllInputs();
					viewModel.SaveAsCommand.Execute(graph);
					viewModel.CloseHomeWorkspaceCommand.Execute(null);
					graphCount += 1;
				}
			}
			batchProcessResults = "Reset all inputs in " + graphCount.ToString() + " graphs...";
			RaisePropertyChanged(nameof(CurrentInputs));
		}

19 Source : UnfancifyViewModel.cs
with MIT License
from andydandy74

public void OnBatchUnfancifyClicked(string directoryPath)
        {
            UnfancifyMsg = "";
            // Read directory contents
            var graphs = System.IO.Directory.EnumerateFiles(directoryPath);
            int graphCount = 0;
            foreach (var graph in graphs)
            {
                var ext = System.IO.Path.GetExtension(graph);
                if (ext == ".dyn")
                {
                    viewModel.OpenCommand.Execute(graph);
                    viewModel.CurrentSpaceViewModel.RunSettingsViewModel.Model.RunType = RunType.Manual;
                    UnfancifyGraph();
                    viewModel.SaveAsCommand.Execute(graph);
                    viewModel.CloseHomeWorkspaceCommand.Execute(null);
                    graphCount += 1;
                    UnfancifyMsg += "Unfancified " + graph + "\n";
                }
            }
            UnfancifyMsg += "Unfancified " + graphCount.ToString() + " graphs...";
        }

19 Source : Program.cs
with MIT License
from ANF-Studios

[SupportedOSPlatform("windows")]
        [UnsupportedOSPlatform("browser")]
        public static void Main(string[] args)
        {
            Console.replacedle = AppDomain.CurrentDomain.FriendlyName;
            if (!OperatingSystem.IsWindows())
                throw new PlatformNotSupportedException("WinPath is Windows only!");
            Parser.Default.ParseVerbs<AddOptions, BackupOptions, UpdateOptions>(args)
                .WithParsed<AddOptions>(options => {
                    if (options.Value == null) HandleArgument(HandleEventType.NoValue);
                    else if (options.Value != null)
                    {
                        if (options.AddToUserVariables && options.AddToSystemVariables)
                            HandleArgument(HandleEventType.UserAndSystemPath, options);
                        else if (options.AddToUserVariables)
                            HandleArgument(HandleEventType.UserPath, options);
                        else if (options.AddToSystemVariables)
                            HandleArgument(HandleEventType.SystemPath, options);
                        else
                            HandleArgument(HandleEventType.NoUserOrSystemPath);
                    }
                })
                //.WithParsed<BackupOptions>(options =>
                //{
                //    Doesn't react/trigger this section.
                //    This is because of child verbs.
                //})
                .WithParsed<BackupOptions.BackupListOptions>(options =>
                {
                    if (options.ListAllBackups)
                        Backup.ListBackups(
                            HandleEventType.ListAllBackups,
                            userPath.BackupDirectory
                        );
                    else if (options.ListLatest)
                        Backup.ListBackups(
                            HandleEventType.ListLatestBackups,
                            userPath.BackupDirectory
                        );
                    else
                        Backup.ListBackups(
                            HandleEventType.ListBackups,
                            userPath.BackupDirectory,
                            null,
                            options.Range
                        );
                })
                .WithParsed<BackupOptions.BackupApplyOptions>(options => Backup.ApplyBackup(options))
                .WithParsed<BackupOptions.BackupCreateOptions>(options => Backup.CreateBackup(options))
                .WithParsed<BackupOptions.BackupRemoveOptions>(options => Backup.RemoveBackup(options))
                .WithParsed<UpdateOptions>(options => {
                    Console.WriteLine("Updating WinPath...");
                    Update update = new Update
                    (
                        options.IncludePrereleases,
                        options.ConfirmDownload,
                        (Runtime.OSArchitecture == Architecture.X86
                            || Runtime.OSArchitecture == Architecture.X64)
                    );
                    Console.WriteLine("Fetching data from the server...");
                    var releases = update.GetReleases();
                    Console.WriteLine("replacedyzing data...");
                    Release? release = update.FilterRelease(releases);
                    
                    // To be removed in v1.0.0.
                    if (release is null)
                    {
                        Console.WriteLine("There is no stable release at the moment, please run this command again with the --prerelease flag.");
                        return;
                    }
                    Console.WriteLine("Parsing data...");
                    ReleaseInfo releaseInfo = new ReleaseInfo
                    {
                        ReleaseName = release?.ReleaseName,
                        TagName = release?.TagName,
                        IsPrerelease = (bool)(release?.IsPrerelease),
                        ReleaseDescription = release?.Description,
                        Releasereplacedet = update.GetreplacedetForProcess((Release)release)!,
                        Updater = (replacedet)release?.replacedets.Find((replacedet) => replacedet.ExecutableName == (
                            update.Is32Or64BitOperatingSystem
                                ? "WinPath.Updater_x86.exe"
                                : "WinPath.Updater_arm.exe" 
                            ))
                    };
                    update.DownloadWinPath(releaseInfo, () => {
                        foreach (string file in
                            Directory.EnumerateFiles(
                                $"{Path.GetTempPath()}WinPath\\download\\"
                        ))
                            try
                            {
                                File.Delete(file);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error cleaning up: " + ex.Message);
                            }
                    });
                });
        }

19 Source : BackupCommandTests.cs
with MIT License
from ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void ApplyUserBackup()
        {
            CreateUserBackupInASpecifiedDirectory();
            var backup = Directory.EnumerateFiles(overrideDirectory).ToArray().FirstOrDefault();
            var backupFile = new FileInfo(backup);

            output.WriteLine(backup);
            output.WriteLine(backupFile.Name);

            Program.Main(
                new string[]
                {
                        "backup",
                        "apply",
                        "--user",
                        "--name",
                        backupFile.Name,
                        "--directory",
                        overrideDirectory
                }
            );
            replacedert.True(File.Exists(Path.Combine(Path.GetTempPath(), "WinPath", "u_backup.txt")));
        }

19 Source : BackupCommandTests.cs
with MIT License
from ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void ApplySystemBackup()
        {
            CreateUserBackup();
            var backup = Directory.EnumerateFiles(overrideDirectory).ToArray().FirstOrDefault();

            output.WriteLine(backup);

            Program.Main(
                new string[]
                {
                    "backup",
                    "apply",
                    "--system",
                    "--name",
                    backup,
                    "--directory",
                    overrideDirectory
                }
            );
        }

19 Source : BackupCommandTests.cs
with MIT License
from ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void ApplyUserAndSystemBackup()
        {
            CreateUserBackup();
            var backup = Directory.EnumerateFiles(overrideDirectory).ToArray().FirstOrDefault();

            output.WriteLine(backup);

            Program.Main(
                new string[]
                {
                    "backup",
                    "apply",
                    "--system",
                    "--user",
                    "--name",
                    backup,
                    "--directory",
                    overrideDirectory
                }
            );
        }

19 Source : BackupCommandTests.cs
with MIT License
from ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void RemoveBackup()
        {
            Backup.CreateBackup(new BackupOptions.BackupCreateOptions
            {
                BackupDirectory = overrideDirectory,
                BackupUserVariables = true,
                BackupSystemVariables = false
            });

            var filename = new FileInfo(Directory.EnumerateFiles(overrideDirectory).ToArray().FirstOrDefault());

            output.WriteLine(filename.Name);
            output.WriteLine(filename.DirectoryName);

            Program.Main(new string[]
            {
                "backup",
                "remove",
                "--name",
                filename.Name,
                "--directory",
                filename.DirectoryName
            });
            System.Threading.Tasks.Task.Delay(100);
            bool fileExists = File.Exists(filename.FullName);
            output.WriteLine($"File exists: {fileExists}.");

            replacedert.False(fileExists ? !fileExists : fileExists);
        }

19 Source : BackupCommandTests.cs
with MIT License
from ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void RemoveBackupWithInvalidDirectory()
        {
            Backup.CreateBackup(new BackupOptions.BackupCreateOptions
            {
                BackupDirectory = overrideDirectory,
                BackupUserVariables = true,
                BackupSystemVariables = false
            });

            var filename = new FileInfo(Directory.EnumerateFiles(overrideDirectory).ToArray().FirstOrDefault());
            var exceptionThrown = false;

            output.WriteLine(filename.Name);
            output.WriteLine(filename.DirectoryName);

            try
            {
                Program.Main(new string[]
                {
                    "backup",
                    "remove",
                    "--name",
                    filename.Name,
                    "--directory",
                    "filename.DirectoryName", // Invalid directory.
                });
            }
            catch
            {
                exceptionThrown = true;
            }
            finally
            {
                replacedert.False(exceptionThrown); // Since it's handled within the code.
            }
        }

19 Source : BackupCommandTests.cs
with MIT License
from ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void RemoveBackupWithTooLongDirectory()
        {
            Backup.CreateBackup(new BackupOptions.BackupCreateOptions
            {
                BackupDirectory = overrideDirectory,
                BackupUserVariables = true,
                BackupSystemVariables = false
            });

            bool exceptionThrown = false;
            FileInfo filename = new FileInfo(Directory.EnumerateFiles(overrideDirectory).ToArray().FirstOrDefault());
            const string tooLongDir = @"C:\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\"
                                    + @"foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\"
                                    + @"foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\"
                                    + @"foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\"
                                    + @"foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\"
                                    + @"foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\"
                                    + @"foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\"
                                    + @"foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\foobar\";

            Directory.CreateDirectory(tooLongDir);

            output.WriteLine(filename.Name);
            output.WriteLine(filename.DirectoryName);
            try
            {
                Program.Main(new string[]
                {
                        "backup",
                        "remove",
                        "--name",
                        filename.Name,
                        "--directory",
                        tooLongDir, // Too long directory.
                });
            }
            catch
            {
                exceptionThrown = true;
            }
            finally
            {
                replacedert.False(exceptionThrown); // Since it's handled by .NET Core.
            }
        }

19 Source : BackupCommandTests.cs
with MIT License
from ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void RemoveBackupWhileFileIsInUse()
        {
            Backup.CreateBackup(new BackupOptions.BackupCreateOptions
            {
                BackupDirectory = overrideDirectory,
                BackupUserVariables = true,
                BackupSystemVariables = false
            });

            bool exceptionThrown = false;
            FileInfo filename = new FileInfo(Directory.EnumerateFiles(overrideDirectory).ToArray().FirstOrDefault());

            output.WriteLine(filename.Name);
            output.WriteLine(filename.DirectoryName);

            StreamReader streamReader = new StreamReader(filename.FullName);
            streamReader.ReadToEnd();

            try
            {
                Program.Main(new string[]
                {
                    "backup",
                    "remove",
                    "--directory",
                    filename.DirectoryName,
                    "--name",
                    filename.Name
                });
            }
            catch
            {
                exceptionThrown = true;
            }
            finally
            {
                replacedert.False(exceptionThrown); // Since it's handled within the code.
            }
        }

19 Source : TimelineManager.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public async void LoadTimelineModels()
        {
            var dir = this.TimelineDirectory;
            if (!Directory.Exists(dir))
            {
                return;
            }

            await WPFHelper.InvokeAsync(() => this.TimelineModels.Clear());

            var sampleDirectory = Path.Combine(dir, "sample");

            var existsSamples =
                CommonHelper.IsDebugMode ||
                !Directory.EnumerateFiles(dir).Where(x =>
                    x.ToLower().EndsWith(".xml") ||
                    x.ToLower().EndsWith(".cshtml")).Any();

            if (existsSamples)
            {
                foreach (var file in Directory.GetFiles(sampleDirectory))
                {
                    if (file.EndsWith(".config") ||
                        file.Contains("SampleInclude"))
                    {
                        continue;
                    }

                    var dest = Path.Combine(dir, Path.GetFileName(file));
                    File.Copy(file, dest, true);
                }

                await Task.Delay(1);
            }

            var reference = Path.Combine(dir, "Reference.cshtml");
            var referenceSample = Path.Combine(sampleDirectory, "Reference.cshtml");
            if (File.Exists(reference) &&
                File.Exists(referenceSample))
            {
                File.Copy(referenceSample, reference, true);
            }

            await Task.Yield();

            // RazorEngine にわたすモデルを更新する
            TimelineModel.RefreshRazorModel();

            var list = new List<TimelineModel>();
            foreach (var file in Directory.EnumerateFiles(dir).Where(x =>
                x.ToLower().EndsWith(".xml") ||
                x.ToLower().EndsWith(".cshtml")))
            {
                try
                {
                    var tl = TimelineModel.Load(file);
                    if (tl != null)
                    {
                        if (tl.HasError)
                        {
                            this.AppLogger.Error(
                                $"{TimelineConstants.LogSymbol} Load error. file={file}\n{tl.ErrorText}");
                            LogManager.Flush();
                        }

                        list.Add(tl);

                        if (!TimelineSettings.Instance.TimelineFiles.Any(x => x.Key == file))
                        {
                            TimelineSettings.Instance.TimelineFiles.Add(new KeyValue<string, bool>()
                            {
                                Key = file,
                                Value = true,
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AppLogger.Error(
                        ex,
                        $"{TimelineConstants.LogSymbol} Load fatal. file={file}");
                    LogManager.Flush();

                    throw new FileLoadException(
                        $"Timeline file load fatal.\n{Path.GetFileName(file)}",
                        ex);
                }

                await Task.Delay(1);
            }

            // グローバルトリガをロードする
            this.globalTriggers.Clear();
            var globals = list.Where(x =>
                x.IsGlobalZone &&
                !x.HasError);

            foreach (var tl in globals)
            {
                this.LoadGlobalTriggers(tl);
                await Task.Delay(1);
            }

            await WPFHelper.InvokeAsync(() =>
            {
                foreach (var tl in this.TimelineModels)
                {
                    if (tl.IsActive)
                    {
                        tl.IsActive = false;
                        tl.Controller.Unload();
                        Thread.Yield();
                    }
                }

                this.TimelineModels.Clear();
                this.TimelineModels.AddRange(
                    from x in list
                    orderby
                    x.SourceFileName.Contains("Reference") ? 0 : 1,
                    x.IsGlobalZone ? 0 : 1,
                    x.SourceFileName
                    select
                    x);
            });
        }

19 Source : ImageSavingService.cs
with MIT License
from AntonyCorbett

public string Execute()
        {
            string result = string.Empty;

            if (_images.Any())
            {
                var baseFileName = GetSuitableFilenameWithoutExtension(_scriptureText);

                if (_images.Count == 1)
                {
                    var path = Path.Combine(_folder, Path.ChangeExtension(baseFileName, ".png"));
                    BitmapWriter.WritePng(path, _images.First());
                    result = path;
                }
                else
                {
                    string folder = Path.Combine(_folder, baseFileName);
                    if (Directory.Exists(folder))
                    {
                        ClearFiles(folder);
                    }
                    else
                    {
                        Directory.CreateDirectory(folder);
                    }

                    if (Directory.Exists(folder))
                    {
                        if (Directory.EnumerateFiles(folder).Any())
                        {
                            throw new Exception("Could not clear folder!");
                        }

                        result = folder;

                        int count = 1;
                        foreach (var image in _images)
                        {
                            var baseNameWithDigitPrefix = $"{count:D3} {baseFileName}";
                            var path = Path.Combine(folder, Path.ChangeExtension(baseNameWithDigitPrefix, ".png"));
                            BitmapWriter.WritePng(path, image);

                            ++count;
                        }
                    }
                }
            }

            return result;
        }

19 Source : Issues.cs
with Apache License 2.0
from Appdynamics

[Ignore]
        [TestMethod]
        public void Issue15154()
        {
            Directory.EnumerateFiles(@"c:\temp\bug\ConstructorInvokationNotThreadSafe\").AsParallel().ForAll(file =>
            {
                //lock (_lock)
                //{
                using (var package = new ExcelPackage(new FileStream(file, FileMode.Open)))
                {
                    package.Workbook.Worksheets[1].Cells[1, 1].Value = file;
                    package.SaveAs(new FileInfo(@"c:\temp\bug\ConstructorInvokationNotThreadSafe\new\" + new FileInfo(file).Name));
                }
                //}
            });

        }

19 Source : Issues.cs
with Apache License 2.0
from Appdynamics

[TestMethod, Ignore]
        public void Issue10()
        {
            var fi = new FileInfo($@"C:\temp\bug\issue10.xlsx");
            if (fi.Exists)
            {
                fi.Delete();
            }
            using (var pck = new ExcelPackage(fi))
            {
                var ws = pck.Workbook.Worksheets.Add("Pictures");
                int row = 1;
                foreach (var f in Directory.EnumerateFiles(@"c:\temp\addin_temp\Addin\img\open_icon_library-full\icons\ico\16x16\actions\"))
                {
                    var b = new Bitmap(f);
                    var pic = ws.Drawings.AddPicture($"Image{(row + 1) / 2}", b);
                    pic.SetPosition(row, 0, 0, 0);
                    row += 2;
                }
                pck.Save();
            }
        }

19 Source : Program.cs
with MIT License
from aschearer

private static void ScanForNewBuilds(object sender, ElapsedEventArgs e)
        {
            Trace.TraceInformation("Scanning for new Unity Cloud Builds at {0:MM/dd/yy H:mm}", DateTime.Now);
            System.Console.WriteLine();

            foreach (var configFile in Directory.EnumerateFiles("configs"))
            {
                if (!configFile.EndsWith("json"))
                {
                    continue;
                }

                Trace.TraceInformation("Processing config file: {0}", Path.GetFileNameWithoutExtension(configFile));

                var buildConfig = JsonConvert.DeserializeObject<BuildConfiguration>(File.ReadAllText(configFile));
                var downloadBuildDataTask = Task.Run(() => DownloadUnityCloudBuildMetadata(buildConfig.UnitySettings));
                downloadBuildDataTask.Wait();
                var latestBuild = downloadBuildDataTask.Result;

                if (latestBuild != null)
                {
                    var successfullyDownloadedBuild = DownloadUnityCloudBuild(buildConfig.SteamSettings, latestBuild);
                    if (successfullyDownloadedBuild)
                    {
                        bool success = UploadBuildToSteamworks(buildConfig.SteamSettings);
                        TryNotifySlack(buildConfig.SteamSettings, latestBuild, success);
                    }
                }

                Trace.TraceInformation("Finished processing config file: {0}", Path.GetFileNameWithoutExtension(configFile));
                System.Console.WriteLine();
            }

            Trace.TraceInformation("Finished scanning for new Unity Cloud Builds");
            Trace.TraceInformation(
                "Checking for new builds in {0} minutes at {1:MM/dd/yy H:mm}",
                pollingFrequencyRaw,
                DateTime.Now + TimeSpan.FromMilliseconds(pollingFrequency));
        }

19 Source : Program.cs
with GNU General Public License v3.0
from ASCOMInitiative

private static void DeleteFiles(string path, string fileSpecifier, string description)
        {
            IEnumerable<string> files = Directory.EnumerateFiles(path).Where(name => Regex.IsMatch(name, fileSpecifier, RegexOptions.IgnoreCase));
            TL.LogMessage("DeleteFiles", string.Format("Found {0} {1} files to delete", files.Count(), description));
            if (files.Count() != 0) // Delete extraneous pdb files
            {
                foreach (string file in files)
                {
                    TL.LogMessage("DeleteFiles", string.Format("Deleting file {0}", file));
                    try
                    {
                        File.Delete(file);
                        TL.LogMessage("DeleteFiles", string.Format("Successfully deleted file {0}", file));
                    }
                    catch (Exception ex)
                    {
                        string errorMessage = string.Format("Unable to delete file {0} - {1}", file, ex.Message);
                        TL.LogMessage("DeleteFiles", errorMessage);
                    }
                }
            }
        }

19 Source : TemplateTestBase.cs
with Apache License 2.0
from aspnet

protected void replacedertEmptyMigration(string migration)
        {
            var fullPath = Path.Combine(TemplateOutputDir, "Data/Migrations");
            var file = Directory.EnumerateFiles(fullPath).Where(f => f.EndsWith($"{migration}.cs")).FirstOrDefault();

            replacedert.NotNull(file);
            var contents = File.ReadAllText(file);

            var emptyMigration = @"protected override void Up(MigrationBuilder migrationBuilder)
        {

        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {

        }";
            
            // This comparison can break depending on how GIT checked out newlines on different files.
            replacedert.Contains(RemoveNewLines(emptyMigration), RemoveNewLines(contents));
        }

19 Source : Themes.cs
with MIT License
from Assistant

public static void LoadThemes()
        {
            loadedThemes.Clear();

            /*
             * Begin by loading local themes. We should always load these first.
             * I am doing loading here to prevent the LoadTheme function from becoming too crazy.
             */
            foreach (string localTheme in preInstalledThemes)
            {
                string location = $"Themes/{localTheme}.xaml";
                Uri local = new Uri(location, UriKind.Relative);

                ResourceDictionary localDictionary = new ResourceDictionary
                {
                    Source = local
                };

                /*
                 * Load any Waifus that come with these built-in themes, too.
                 * The format must be: Background.png and Sidebar.png as a subfolder with the same name as the theme name.
                 * For example: "Themes/Dark/Background.png", or "Themes/Ugly Kulu-Ya-Ku/Sidebar.png"
                 */
                Waifus waifus = new Waifus
                {
                    Background = GetImageFromEmbeddedResources(localTheme, "Background"),
                    Sidebar = GetImageFromEmbeddedResources(localTheme, "Sidebar")
                };

                Theme theme = new Theme(localTheme, localDictionary)
                {
                    Waifus = waifus
                };

                loadedThemes.Add(localTheme, theme);
            }

            // Load themes from Themes subfolder if it exists.
            if (Directory.Exists(ThemeDirectory))
            {
                foreach (string file in Directory.EnumerateFiles(ThemeDirectory))
                {
                    FileInfo info = new FileInfo(file);
                    string name = Path.GetFileNameWithoutExtension(info.Name);

                    if (info.Extension.ToLower().Equals(".mat"))
                    {
                        Theme theme = LoadZipTheme(ThemeDirectory, name, ".mat");
                        if (theme is null) continue;

                        AddOrModifyTheme(name, theme);
                    }
                }

                // Finally load any loose theme files in subfolders.
                foreach (string directory in Directory.EnumerateDirectories(ThemeDirectory))
                {
                    string name = directory.Split('\\').Last();
                    Theme theme = LoadTheme(directory, name);

                    if (theme is null) continue;
                    AddOrModifyTheme(name, theme);
                }
            }

            // Refresh Themes dropdown in Options screen.
            if (Options.Instance != null && Options.Instance.ApplicationThemeComboBox != null)
            {
                Options.Instance.ApplicationThemeComboBox.ItemsSource = LoadedThemes;
                Options.Instance.ApplicationThemeComboBox.SelectedIndex = LoadedThemes.IndexOf(LoadedTheme);
            }
        }

19 Source : Themes.cs
with MIT License
from Assistant

private static Theme LoadTheme(string directory, string name)
        {
            Theme theme = new Theme(name, null)
            {
                Waifus = new Waifus()
            };

            foreach (string file in Directory.EnumerateFiles(directory).OrderBy(x => x))
            {
                FileInfo info = new FileInfo(file);
                bool isPng = info.Name.EndsWith(".png", StringComparison.OrdinalIgnoreCase);
                bool isSidePng = info.Name.EndsWith(".side.png", StringComparison.OrdinalIgnoreCase);
                bool isXaml = info.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase);

                if (isPng && !isSidePng)
                {
                    theme.Waifus.Background = new BitmapImage(new Uri(info.FullName));
                }

                if (isSidePng)
                {
                    theme.Waifus.Sidebar = new BitmapImage(new Uri(info.FullName));
                }

                if (isXaml)
                {
                    try
                    {
                        Uri resourceSource = new Uri(info.FullName);
                        ResourceDictionary dictionary = new ResourceDictionary
                        {
                            Source = resourceSource
                        };

                        theme.ThemeDictionary = dictionary;
                    }
                    catch (Exception ex)
                    {
                        string message = string.Format((string)Application.Current.FindResource("Themes:FailedToLoadXaml"), name, ex.Message);
                        MessageBox.Show(message);
                    }
                }

                if (supportedVideoExtensions.Contains(info.Extension))
                {
                    if (info.Name != $"_{name}{info.Extension}" || theme.VideoLocation is null)
                    {
                        theme.VideoLocation = info.FullName;
                    }
                }
            }

            return theme;
        }

19 Source : UnityPackageExporter.cs
with Apache License 2.0
from aws

public static void Export()
    {
        var exportedPackagereplacedetList = Directory.EnumerateDirectories("replacedets")
            .Except(new string[]
            {
                "replacedets\\Editor",
                "replacedets\\Tests",
            })
            .ToList();


        Debug.Log("Exporting Sample Game...");

        exportedPackagereplacedetList.AddRange(Directory.EnumerateFiles("replacedets"));
        exportedPackagereplacedetList.Add("replacedets\\Editor\\Scripts\\GameLiftClientSettingsMenu.cs");
        exportedPackagereplacedetList.Add("replacedets\\Editor\\Scripts\\ClientServerSwitchMenu.cs");

        string outputFolder = @"..";

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

        string outputPath = Path.Combine(outputFolder, "SampleGame.unitypackage");

        replacedetDatabase.ExportPackage(exportedPackagereplacedetList.ToArray(), outputPath,
            ExportPackageOptions.Recurse | ExportPackageOptions.IncludeDependencies);

        Debug.Log("Sample Game exported to " + outputPath);
    }

19 Source : U8Archive.cs
with MIT License
from Big-Endian-32

public List<IArchiveData> GetFilesFromDirectory(string path, bool includeSubdirectories = false)
        {
            U8ArchiveDirectory dir = new()
            {
                Name = Path.GetFileName(path)
            };

            foreach (string filePath in Directory.EnumerateFiles(path))
            {
                U8ArchiveFile file = new(filePath)
                {
                    Parent = dir,
                };

                Logger.Log($"Loading {Path.GetFileName(filePath)}...", Interfaces.LogLevel.Utility, null);

                dir.Add(file);
            }

            if (includeSubdirectories)
            {
                foreach (string subdirectory in Directory.EnumerateDirectories(path))
                {
                    dir.Add
                    (
                        new U8ArchiveDirectory()
                        {
                            Name = Path.GetFileName(subdirectory),
                            Parent = dir,
                            Data = GetFilesFromDirectory(subdirectory, includeSubdirectories)
                        }
                    );
                }
            }

            return dir.Data;
        }

19 Source : RootPage.xaml.cs
with GNU General Public License v3.0
from Bililive

private async void RootPage_Loaded(object sender, RoutedEventArgs e)
#pragma warning restore VSTHRD100 // Avoid async void methods
        {
            // 上次选择的路径信息
            var pathInfo = this.workDirectoryLoader.Read();
            // 第一次尝试从命令行和配置文件自动选择路径
            var first_time = true;
            // 如果是从命令行参数传入的路径,则不保存选择的路径到文件
            var from_argument = false;

            // 路径选择错误
            var error = WorkDirectorySelectorDialog.WorkDirectorySelectorDialogError.None;
            // 最终选择的路径
            string path;

            while (true)
            {
                try
                {
                    // 获取一个路径
                    if (first_time)
                    {
                        // while 循环第一次运行时检查命令行参数、和上次选择记住的路径
                        try
                        {
                            first_time = false;

                            if (!string.IsNullOrWhiteSpace(CommandArgumentRecorderPath))
                            {
                                // 如果有参数直接跳到检查路径
                                logger.Debug("Using path from command argument");
                                path = Path.GetFullPath(CommandArgumentRecorderPath);
                                from_argument = true; // 用于控制不写入文件保存
                            }
                            else if (pathInfo.SkipAsking && !CommandArgumentAskPath)
                            {
                                logger.Debug("Using path from path.json file");
                                // 上次选择了“不再询问”
                                path = pathInfo.Path;
                            }
                            else
                            {
                                // 无命令行参数 和 记住选择
                                continue;
                            }
                        }
                        catch (Exception)
                        {
                            // 出错直接重新来,不显示 error
                            continue;
                        }
                    }
                    else
                    {
                        // 尝试读取上次选择的路径
                        var lastdir = pathInfo.Path;

                        // 显示路径选择界面
                        var dialog = new WorkDirectorySelectorDialog
                        {
                            Error = error,
                            Path = lastdir,
                            SkipAsking = pathInfo.SkipAsking
                        };
                        var dialogResult = await dialog.ShowAsync();
                        switch (dialogResult)
                        {
                            case ContentDialogResult.Primary:
                                logger.Debug("Confirm path selected");
                                break;
                            case ContentDialogResult.Secondary:
                                logger.Debug("Toolbox mode selected");
                                return;
                            case ContentDialogResult.None:
                            default:
                                logger.Debug("Exit selected");
                                (Application.Current.MainWindow as NewMainWindow)!.CloseWithoutConfirmAction();
                                return;
                        }

                        pathInfo.SkipAsking = dialog.SkipAsking;

                        try
                        { path = Path.GetFullPath(dialog.Path); }
                        catch (Exception)
                        {
                            error = WorkDirectorySelectorDialog.WorkDirectorySelectorDialogError.PathNotSupported;
                            continue;
                        }
                    }
                    // 获取一个路径结束

                    var configFilePath = Path.Combine(path, "config.json");

                    if (!Directory.Exists(path))
                    {
                        error = WorkDirectorySelectorDialog.WorkDirectorySelectorDialogError.PathDoesNotExist;
                        continue;
                    }
                    else if (!Directory.EnumerateFiles(path).Any())
                    {
                        // 可用的空文件夹
                    }
                    else if (!File.Exists(configFilePath))
                    {
                        error = WorkDirectorySelectorDialog.WorkDirectorySelectorDialogError.PathContainsFiles;
                        continue;
                    }

                    // 已经选定工作目录

                    // 如果不是从命令行参数传入的路径,写入 lastdir_path 记录
                    try
                    {
                        if (!from_argument)
                        {
                            pathInfo.Path = path;
                            this.workDirectoryLoader.Write(pathInfo);
                        }
                    }
                    catch (Exception) { }

                    // 加载配置文件
                    var config = ConfigParser.LoadFrom(path);
                    if (config is null)
                    {
                        error = WorkDirectorySelectorDialog.WorkDirectorySelectorDialogError.FailedToLoadConfig;
                        continue;
                    }
                    config.Global.WorkDirectory = path;

                    // 检查已经在同目录运行的其他进程
                    if (!SingleInstance.CheckMutex(path))
                    {
                        // 有已经在其他目录运行的进程,已经通知该进程,本进程退出
                        (Application.Current.MainWindow as NewMainWindow)!.CloseWithoutConfirmAction();
                        return;
                    }

                    // 无已经在同目录运行的进程
                    this.serviceProvider = this.BuildServiceProvider(config, logger);
                    ServiceProvider = this.serviceProvider;
                    var recorder = this.serviceProvider.GetRequiredService<IRecorder>();

                    this.Model.Recorder = recorder;
                    this.RoomListPageNavigationViewItem.IsEnabled = true;
                    this.SettingsPageNavigationViewItem.IsEnabled = true;
                    (Application.Current.MainWindow as NewMainWindow)!.HideToTray = true;

                    _ = Task.Run(async () =>
                    {
                        await Task.Delay(150);
                        _ = this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, method: new Action(() =>
                        {
                            this.RoomListPageNavigationViewItem.IsSelected = true;

                            if (CommandArgumentHide)
                                Application.Current.MainWindow.WindowState = WindowState.Minimized;
                        }));
                    });

                    break;
                }
                catch (Exception ex)
                {
                    error = WorkDirectorySelectorDialog.WorkDirectorySelectorDialogError.UnknownError;
                    logger.Warning(ex, "选择工作目录时发生了未知错误");
                    continue;
                }
            }
        }

19 Source : Disk.cs
with MIT License
from BootGen

private IEnumerable<VirtualFile> GetFiles(string path)
        {
            foreach(var fileName in Directory.EnumerateFiles(path)) {
                yield return new VirtualFile {
                    Path = path,
                    Name = Path.GetFileName(fileName),
                    Content = File.ReadAllText(fileName)
                };
            }
            foreach(var subPath in Directory.EnumerateDirectories(path))
                foreach (var file in GetFiles(subPath))
                    yield return file;
        }

19 Source : CertificateGenerator.cs
with Apache License 2.0
from buehler

private async Task ListDir(string directory)
        {
            await _appOut.WriteLineAsync($"Files in {directory}:");
            foreach (var file in Directory.EnumerateFiles(directory))
            {
                await _appOut.WriteLineAsync(file);
            }
        }

19 Source : FileService.cs
with GNU General Public License v3.0
from bykovme

public IEnumerable<string> GetFilePaths(string path)
		{
			try {
				return Directory.EnumerateFiles(path);
			} catch (DirectoryNotFoundException ex) {
				Directory.CreateDirectory(path);
				log(ex.Message, nameof(GetFilePaths));
				return Directory.EnumerateFiles(path);
			}
		}

19 Source : FileService.cs
with GNU General Public License v3.0
from bykovme

public IEnumerable<string> GetFilePaths(string path)
		{
			try
			{
				return Directory.EnumerateFiles(path);
			}
			catch (DirectoryNotFoundException ex)
			{
				Directory.CreateDirectory(path);
				AppLogs.Log(ex.Message, nameof(GetFilePaths), nameof(FileService));
				return Directory.EnumerateFiles(path);
			}
		}

19 Source : FileService.cs
with GNU General Public License v3.0
from bykovme

public IEnumerable<string> GetFileNames(string path)
		{
			if (RequestPermissionsManager.ReadWriteStoragePermission() == true) {
				try {
					return Directory.EnumerateFiles(path).Select(f => Path.GetFileName(f));
				} catch (DirectoryNotFoundException ex) {
					Directory.CreateDirectory(path);
					log(ex.Message, nameof(GetFileNames));
					return Directory.EnumerateFiles(path).Select(f => Path.GetFileName(f));
				} catch (Exception ex) {
					log(ex.Message, nameof(GetFileNames));
					return null;
				}
			}
			return null;
		}

19 Source : StartupRunner.cs
with Apache License 2.0
from cairoshell

private List<StartupEntry> GetAppsFromDirectory(StartupLocation location)
        {
            List<StartupEntry> startupApps = new List<StartupEntry>();
            List<string> disallowedItems = GetDisallowedItems(location);
            string locationExpanded = Environment.ExpandEnvironmentVariables(location.Location);

            try
            {
                if (ShellHelper.Exists(locationExpanded))
                {
                    foreach (string startupFile in Directory.EnumerateFiles(locationExpanded))
                    {
                        if (!ShellHelper.IsFileVisible(startupFile))
                        {
                            continue;
                        }
                        
                        // only add items that are not disabled
                        if (!disallowedItems.Contains(Path.GetFileName(startupFile)))
                        {
                            startupApps.Add(new StartupEntry
                            {
                                Location = location,
                                Path = startupFile
                            });
                        }
                    }
                }
            }
            catch
            {
                ShellLogger.Warning($"StartupRunner: Unable to load startup items from directory {location}");
            }

            return startupApps;
        }

19 Source : MapFile.cs
with Apache License 2.0
from Capnode

public static IEnumerable<MapFile> GetMapFiles(string mapFileDirectory, string market)
        {
            var mapFiles = new ConcurrentBag<MapFile>();
            Parallel.ForEach(Directory.EnumerateFiles(mapFileDirectory), file =>
            {
                if (file.EndsWith(".csv"))
                {
                    var permtick = Path.GetFileNameWithoutExtension(file);
                    var fileRead = SafeMapFileRowRead(file, market);
                    mapFiles.Add(new MapFile(permtick, fileRead));
                }
            });
            return mapFiles;
        }

19 Source : CustomDriverDevelopViewModel.cs
with Apache License 2.0
from cdy816

private void ListTemplate()
        {
            List<string> ltmp = new List<string>();
            string stmp = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "CustomTemplate");
            if(!System.IO.Directory.Exists(stmp))
            {
                System.IO.Directory.CreateDirectory(stmp);
            }
            foreach(var vv in System.IO.Directory.EnumerateFiles(stmp))
            {
                ltmp.Add(System.IO.Path.GetFileName(vv));
            }
            CustomTemplates = ltmp;
        }

19 Source : FileSystemCompletionHelper.cs
with Apache License 2.0
from cdy816

protected virtual IEnumerable<string> EnumerateFiles(string fullDirectoryPath)
        {
            Debug.replacedert(PathUtilities.IsAbsolute(fullDirectoryPath));
            return IOUtilities.PerformIO(() => Directory.EnumerateFiles(fullDirectoryPath), Array.Empty<string>());
        }

19 Source : CefNetCodeGen.cs
with MIT License
from CefNet

public void Generate()
		{
			foreach (string filename in Directory.EnumerateFiles(InputPath))
			{
				string source = File.ReadAllText(filename, Encoding.UTF8);
				if (!source.Contains("Role: Handler"))
					continue;

				SyntaxTree tree = CSharpSyntaxTree.ParseText(source, path: filename, encoding: Encoding.UTF8);
				CompilationUnitSyntax unit = (CompilationUnitSyntax)tree.GetRoot();

				string handlerClreplacedName = Path.GetFileNameWithoutExtension(filename);
				GenerateFileCode(GeneratePrivateInterfaceFileCode, Path.Combine(OutputPath, "I" + handlerClreplacedName + "Private.cs"), unit);

				if (handlerClreplacedName == "CefApp")
					continue;

				GenerateFileCode(GenerateHandlerGlueFileCode, Path.Combine(OutputPath, handlerClreplacedName + "Glue.cs"), unit);
			}
		}

19 Source : AllTransactionStore.cs
with GNU General Public License v3.0
from chaincase-app

private void EnsureBackwardsCompatibility()
		{
			try
			{
				// Before Wasabi 1.1.7
				var networkIndependentTransactionsFolderPath = Path.Combine(EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client")), "Transactions");
				if (Directory.Exists(networkIndependentTransactionsFolderPath))
				{
					var oldTransactionsFolderPath = Path.Combine(networkIndependentTransactionsFolderPath, Network.Name);
					if (Directory.Exists(oldTransactionsFolderPath))
					{
						lock (Lock)
						{
							foreach (var filePath in Directory.EnumerateFiles(oldTransactionsFolderPath))
							{
								try
								{
									string jsonString = File.ReadAllText(filePath, Encoding.UTF8);
									var allWalletTransactions = JsonConvert.DeserializeObject<IEnumerable<SmartTransaction>>(jsonString)?.OrderByBlockchain() ?? Enumerable.Empty<SmartTransaction>();
									foreach (var tx in allWalletTransactions)
									{
										AddOrUpdateNoLock(tx);
									}

									File.Delete(filePath);
								}
								catch (Exception ex)
								{
									Logger.LogTrace(ex);
								}
							}

							Directory.Delete(oldTransactionsFolderPath, recursive: true);
						}
					}

					// If all networks successfully migrated, too, then delete the transactions folder, too.
					if (!Directory.EnumerateFileSystemEntries(networkIndependentTransactionsFolderPath).Any())
					{
						Directory.Delete(networkIndependentTransactionsFolderPath, recursive: true);
					}
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Backwards compatibility could not be ensured.");
				Logger.LogWarning(ex);
			}
		}

19 Source : IoTests.cs
with GNU General Public License v3.0
from chaincase-app

[Fact]
		public async Task IoManagerTestsAsync()
		{
			var file1 = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName(), $"file1.dat");
			var file2 = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName(), $"file2.dat");

			Random random = new Random();
			List<string> lines = new List<string>();
			for (int i = 0; i < 1000; i++)
			{
				string line = new string(Enumerable.Repeat(Constants.Chars, 100)
					.Select(s => s[random.Next(s.Length)]).ToArray());

				lines.Add(line);
			}

			// Single thread file operations.

			DigestableSafeMutexIoManager ioman1 = new DigestableSafeMutexIoManager(file1);

			// Delete the file if Exist.

			ioman1.DeleteMe();
			replacedert.False(ioman1.Exists());

			replacedert.False(File.Exists(ioman1.DigestFilePath));

			// Write the data to the file.

			await ioman1.WriteAllLinesAsync(lines);
			replacedert.True(ioman1.Exists());

			// Check if the digest file is created.

			replacedert.True(File.Exists(ioman1.DigestFilePath));

			// Read back the content and check.

			static bool IsStringArraysEqual(string[] lines1, string[] lines2)
			{
				if (lines1.Length != lines2.Length)
				{
					return false;
				}

				for (int i = 0; i < lines1.Length; i++)
				{
					string line = lines2[i];
					var readLine = lines1[i];

					if (!line.Equals(readLine))
					{
						return false;
					}
				}
				return true;
			}

			var readLines = await ioman1.ReadAllLinesAsync();

			replacedert.True(IsStringArraysEqual(readLines, lines.ToArray()));

			// Check digest file, and write only differ logic.

			// Write the same content, file should not be written.
			var currentDate = File.GetLastWriteTimeUtc(ioman1.FilePath);
			await Task.Delay(500);
			await ioman1.WriteAllLinesAsync(lines);
			var noChangeDate = File.GetLastWriteTimeUtc(ioman1.FilePath);
			replacedert.Equal(currentDate, noChangeDate);

			// Write different content, file should be written.
			currentDate = File.GetLastWriteTimeUtc(ioman1.FilePath);
			await Task.Delay(500);
			lines.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
			await ioman1.WriteAllLinesAsync(lines);
			var newContentDate = File.GetLastWriteTimeUtc(ioman1.FilePath);
			replacedert.NotEqual(currentDate, newContentDate);

			/* The next test is commented out because on mac and on linux File.Open does not lock the file
			 * it can be still written by the ioman1.WriteAllLinesAsync(). Tried with FileShare.None FileShare.Delete
			 * FileStream.Lock none of them are working or caused not supported on this platform exception.
			 * So there is no OP system way to guarantee that the file won't be written during another write operation.
			 * For example git is using lock files to solve this problem. We are using system wide mutexes.
			 * For now there is no other way to do this. Some useful links :
			 * https://stackoverflow.com/questions/2751734/how-do-filesystems-handle-concurrent-read-write
			 * https://github.com/dotnet/corefx/issues/5964
			 */

			//using (File.OpenWrite(ioman1.FilePath))
			//{
			//	// Should be OK because the same data is written.
			//	await ioman1.WriteAllLinesAsync(lines);
			//}
			//using (File.OpenWrite(ioman1.FilePath))
			//{
			//	// Should fail because different data is written.
			//	await replacedert.ThrowsAsync<IOException>(async () => await ioman1.WriteAllLinesAsync(lines));
			//}

			await ioman1.WriteAllLinesAsync(lines);

			// Simulate file write error and recovery logic.

			// We have only *.new and *.old files.
			File.Copy(ioman1.FilePath, ioman1.OldFilePath);
			File.Move(ioman1.FilePath, ioman1.NewFilePath);

			// At this point there is now OriginalFile.

			var newFile = await ioman1.ReadAllLinesAsync();

			replacedert.True(IsStringArraysEqual(newFile, lines.ToArray()));

			// Add one more line to have different data.
			lines.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");

			await ioman1.WriteAllLinesAsync(lines);

			// Check recovery mechanism.

			replacedert.True(
				File.Exists(ioman1.FilePath) &&
				!File.Exists(ioman1.OldFilePath) &&
				!File.Exists(ioman1.NewFilePath));

			ioman1.DeleteMe();

			replacedert.False(ioman1.Exists());

			// Check if directory is empty.

			var fileCount = Directory.EnumerateFiles(Path.GetDirectoryName(ioman1.FilePath)).Count();
			replacedert.Equal(0, fileCount);

			// Check Mutex usage on simultaneous file writes.

			DigestableSafeMutexIoManager ioman2 = new DigestableSafeMutexIoManager(file2);

			await Task.Run(async () =>
			{
				using (await ioman1.Mutex.LockAsync())
				{
					// Should not be a problem because they use different Mutexes.
					using (await ioman2.Mutex.LockAsync())
					{
						await ioman1.WriteAllLinesAsync(lines);
						await ioman2.WriteAllLinesAsync(lines);
						ioman1.DeleteMe();
						ioman2.DeleteMe();
					}
				}
			});

			// TryReplace test.
			var dummyFilePath = $"{ioman1.FilePath}dummy";
			var dummyContent = new string[]
			{
				"banana",
				"peach"
			};
			await File.WriteAllLinesAsync(dummyFilePath, dummyContent);

			await ioman1.WriteAllLinesAsync(lines);

			ioman1.TryReplaceMeWith(dummyFilePath);

			var fruits = await ioman1.ReadAllLinesAsync();

			replacedert.True(IsStringArraysEqual(dummyContent, fruits));

			replacedert.False(File.Exists(dummyFilePath));

			ioman1.DeleteMe();
		}

19 Source : TestGenerator.cs
with MIT License
from circles-arrows

private void DeleteDirAndFiles(string dirPath)
        {
            foreach (string file in Directory.EnumerateFiles(dirPath))
                File.Delete(file);

            if (Directory.GetFiles(dirPath).Length == 0)
                Directory.Delete(dirPath);
        }

19 Source : UniquePathFixture.cs
with MIT License
from cloudtoid

public void Dispose()
        {
            foreach (var file in Directory.EnumerateFiles(Path))
                PathUtil.TryDeleteFile(file);

            try
            {
                Directory.Delete(Path);
            }
            catch { }
        }

19 Source : GameContext.cs
with MIT License
from CommitteeOfZero

private static async Task<(GlyphRasterizer, FontConfiguration)> LoadFonts(
            Configuration configuration)
        {
            var glyphRasterizer = new GlyphRasterizer();
            var defaultFont = new FontFaceKey(configuration.FontFamily, FontStyle.Regular);
            var defaultFontConfig = new FontConfiguration(
                defaultFont,
                italicFont: null,
                new PtFontSize(configuration.FontSize),
                defaultTextColor: RgbaFloat.White.ToVector4(),
                defaultOutlineColor: RgbaFloat.Black.ToVector4(),
                rubyFontSizeMultiplier: 0.4f
            );

            if (OperatingSystem.IsWindows())
            {
                string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
                await glyphRasterizer.AddFontAsync($"{windir}\\Fonts\\msgothic.ttc");
            }
            if (Directory.Exists("Fonts"))
            {
                await glyphRasterizer.AddFontsAsync(Directory.EnumerateFiles("Fonts"));
            }

            return (glyphRasterizer, defaultFontConfig);
        }

19 Source : Program.cs
with MIT License
from CommitteeOfZero

private static void CompileAll(string inputDirectory, string outputDirectory)
        {
            Directory.CreateDirectory(outputDirectory);
            IEnumerable<string> files = Directory.EnumerateFiles(inputDirectory);

            var shaderSets =
                from path in files
                let vert = path.EndsWith("vert")
                let frag = path.EndsWith("frag")
                where vert || frag
                let name = Path.GetFileNameWithoutExtension(path)
                group (path, vert, frag) by name into g
                where g.Count() == 2
                select new
                {
                    Name = g.Key,
                    Vertex = g.FirstOrDefault(x => x.vert).path,
                    Fragment = g.FirstOrDefault(x => x.frag).path,
                };

            foreach (var shaderSet in shaderSets)
            {
                string outputBase = Path.Combine(outputDirectory, shaderSet.Name);
                byte[] vs = File.ReadAllBytes(shaderSet.Vertex);
                byte[] fs = File.ReadAllBytes(shaderSet.Fragment);

                string vsSource = Encoding.UTF8.GetString(vs);
                string fsSource = Encoding.UTF8.GetString(fs);

                var debugCompileOptions = new GlslCompileOptions(debug: true);
                var vsSpvDebugOutput = SpirvCompilation.CompileGlslToSpirv(
                    vsSource, string.Empty, ShaderStages.Vertex,
                    debugCompileOptions);
                var fsSpvDebugOutput = SpirvCompilation.CompileGlslToSpirv(
                    fsSource, string.Empty, ShaderStages.Fragment,
                    debugCompileOptions);

                var releaseCompileOptions = new GlslCompileOptions(debug: false);
                var vsSpvReleaseOutput = SpirvCompilation.CompileGlslToSpirv(
                    vsSource, string.Empty, ShaderStages.Vertex,
                    releaseCompileOptions);
                var fsSpvReleaseOutput = SpirvCompilation.CompileGlslToSpirv(
                    fsSource, string.Empty, ShaderStages.Fragment,
                    releaseCompileOptions);
                File.WriteAllBytes(outputBase + "-vertex.450.glsl.spv", vsSpvReleaseOutput.SpirvBytes);
                File.WriteAllBytes(outputBase + "-fragment.450.glsl.spv", fsSpvDebugOutput.SpirvBytes);

                var glCompileOptions = new CrossCompileOptions(fixClipSpaceZ: true, invertVertexOutputY: false);
                var glslResult = SpirvCompilation.CompileVertexFragment(
                    vsSpvDebugOutput.SpirvBytes,
                    fsSpvDebugOutput.SpirvBytes,
                    CrossCompileTarget.GLSL,
                    glCompileOptions);
                File.WriteAllText(outputBase + "-vertex.330.glsl", glslResult.VertexShader);
                File.WriteAllText(outputBase + "-fragment.330.glsl", glslResult.FragmentShader);

                var esslResult = SpirvCompilation.CompileVertexFragment(
                    vsSpvDebugOutput.SpirvBytes,
                    fsSpvDebugOutput.SpirvBytes,
                    CrossCompileTarget.ESSL,
                    glCompileOptions);
                File.WriteAllText(outputBase + "-vertex.300.glsles", glslResult.VertexShader);
                File.WriteAllText(outputBase + "-fragment.300.glsles", glslResult.FragmentShader);

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    var hlslDebugOutput = SpirvCompilation.CompileVertexFragment(
                        vsSpvDebugOutput.SpirvBytes,
                        fsSpvDebugOutput.SpirvBytes,
                        CrossCompileTarget.HLSL);
                    File.WriteAllText(outputBase + "-vertex.hlsl", hlslDebugOutput.VertexShader);
                    File.WriteAllText(outputBase + "-fragment.hlsl", hlslDebugOutput.FragmentShader);

                    var hlslReleaseOutput = SpirvCompilation.CompileVertexFragment(
                        vsSpvReleaseOutput.SpirvBytes,
                        fsSpvReleaseOutput.SpirvBytes,
                        CrossCompileTarget.HLSL);

                    byte[] vertBytes = Encoding.UTF8.GetBytes(hlslReleaseOutput.VertexShader);
                    byte[] fragBytes = Encoding.UTF8.GetBytes(hlslReleaseOutput.FragmentShader);
                    File.WriteAllBytes(outputBase + "-vertex.hlsl.bytes", CompileHlsl(ShaderStages.Vertex, vertBytes));
                    File.WriteAllBytes(outputBase + "-fragment.hlsl.bytes", CompileHlsl(ShaderStages.Fragment, fragBytes));
                }
            }
        }

19 Source : InstrumentationHelper.cs
with MIT License
from coverlet-coverage

public string[] GetCoverableModules(string moduleOrAppDirectory, string[] directories, bool includeTestreplacedembly)
        {
            Debug.replacedert(directories != null);
            Debug.replacedert(moduleOrAppDirectory != null);

            bool isAppDirectory = !File.Exists(moduleOrAppDirectory) && Directory.Exists(moduleOrAppDirectory);
            string moduleDirectory = isAppDirectory ? moduleOrAppDirectory : Path.GetDirectoryName(moduleOrAppDirectory);

            if (moduleDirectory == string.Empty)
            {
                moduleDirectory = Directory.GetCurrentDirectory();
            }

            var dirs = new List<string>()
            {
                // Add the test replacedembly's directory.
                moduleDirectory
            };

            // Prepare all the directories we probe for modules.
            foreach (string directory in directories)
            {
                if (string.IsNullOrWhiteSpace(directory)) continue;

                string fullPath = (!Path.IsPathRooted(directory)
                    ? Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), directory))
                    : directory).TrimEnd('*');

                if (!Directory.Exists(fullPath)) continue;

                if (directory.EndsWith("*", StringComparison.Ordinal))
                    dirs.AddRange(Directory.GetDirectories(fullPath));
                else
                    dirs.Add(fullPath);
            }

            // The module's name must be unique.
            var uniqueModules = new HashSet<string>();

            if (!includeTestreplacedembly && !isAppDirectory)
                uniqueModules.Add(Path.GetFileName(moduleOrAppDirectory));

            return dirs.SelectMany(d => Directory.EnumerateFiles(d))
                .Where(m => Isreplacedembly(m) && uniqueModules.Add(Path.GetFileName(m)))
                .ToArray();
        }

19 Source : FileSystem.cs
with MIT License
from csinkers

public IEnumerable<string> EnumerateDirectory(string path, string filter = null)
            => filter == null ? Directory.EnumerateFiles(path) : Directory.EnumerateFiles(path, filter);

19 Source : SanityCheckHelper.cs
with GNU General Public License v3.0
from CyanLabs

public static async Task<bool> CancelDownloadCheck(USBHelper.Drive selectedDrive)
        {
            // Set local variables to the values of application level variables
            string driveLetter = AppMan.App.DriveLetter;
            string downloadPath = AppMan.App.DownloadPath;

            // Ensure drive letter is not used as download path
            if (!string.IsNullOrEmpty(driveLetter))
                if (downloadPath.Contains(driveLetter))
                {
                    await Application.Current.Dispatcher.BeginInvoke(() => UIHelper.ShowErrorDialog(LM.GetValue("MessageBox.CancelDownloadIsDrive")));
                    return true;
                }

            // Optional Format
            if (string.IsNullOrWhiteSpace(selectedDrive?.Path) && driveLetter != null)
            {
                try
                {
                    if (Directory.EnumerateFileSystemEntries(driveLetter, "*", SearchOption.AllDirectories).Any())
                    {
                        if (await Application.Current.Dispatcher.Invoke(() => UIHelper.ShowDialog(string.Format(LM.GetValue("MessageBox.OptionalFormat"), driveLetter), LM.GetValue("String.Notice"), LM.GetValue("String.No"),
                            LM.GetValue("String.Yes"))) == ContentDialogResult.Primary)
                        {
                            AppMan.App.SkipFormat = false;
                        }
                        else
                        {
                            AppMan.Logger.Info("Selected folder will not be cleared before being used");
                            AppMan.App.SkipFormat = true;
                        }
                    }
                    else
                    {
                        AppMan.App.SkipFormat = true;
                    }
                }
                catch (DirectoryNotFoundException e)
                {
                    await Application.Current.Dispatcher.BeginInvoke(() => UIHelper.ShowErrorDialog(e.GetFullMessage()));
                    return true;
                }
                catch (IOException e)
                {
                    await Application.Current.Dispatcher.BeginInvoke(() => UIHelper.ShowErrorDialog(e.GetFullMessage()));
                    return true;
                }
                
            }
            else
            {
                if (selectedDrive?.FileSystem == "exFAT" && selectedDrive?.ParreplacedionType == "MBR" && selectedDrive?.VolumeName == "CYANLABS")
                {
                    if (await Application.Current.Dispatcher.Invoke(() => UIHelper.ShowDialog(string.Format(LM.GetValue("MessageBox.OptionalFormatUSB"), selectedDrive.Name, driveLetter), LM.GetValue("String.Notice"),
                        LM.GetValue("String.No"), LM.GetValue("String.Yes"))) == ContentDialogResult.Primary)
                    {
                        AppMan.App.SkipFormat = false;
                    }
                    else
                    {
                        AppMan.Logger.Info("USB Drive not formatted, using existing filesystem and files");
                        AppMan.App.SkipFormat = true;
                    }
                }
            }

            // Format USB Drive
            if (selectedDrive != null && !string.IsNullOrWhiteSpace(selectedDrive.Path) && !AppMan.App.SkipFormat)
                if (await Application.Current.Dispatcher.Invoke(() => UIHelper.ShowWarningDialog(string.Format(LM.GetValue("MessageBox.CancelFormatUSB"), selectedDrive.Name, driveLetter), LM.GetValue("String.Warning") + "!",
                    LM.GetValue("String.No"), LM.GetValue("String.Yes"))) != ContentDialogResult.Primary)
                    return true;

            if (selectedDrive != null && selectedDrive?.Name == LM.GetValue("Home.NoUSBDir"))
            {
                AppMan.Logger.Info("Using 'Select a Directory' instead of a USB Drive");
                AppMan.App.DownloadToFolder = true;
                if (string.IsNullOrEmpty(driveLetter)) return true;

                if (Directory.EnumerateFiles(driveLetter).Any() && !AppMan.App.SkipFormat)
                    if (await Application.Current.Dispatcher.Invoke(() => UIHelper.ShowWarningDialog(string.Format(LM.GetValue("MessageBox.CancelDeleteFiles"), driveLetter), LM.GetValue("String.Warning") + "!",
                        LM.GetValue("String.No"), LM.GetValue("String.Yes"))) != ContentDialogResult.Primary)
                        return true;
            }
            else
            {
                AppMan.App.DownloadToFolder = false;
            }

            // If nothing above has returned true then download has not been cancelled and method will return false;
            return false;
        }

19 Source : JsonLoader.cs
with GNU General Public License v3.0
from d8ahazard

public List<T> LoadFiles<T>() {
			var output = new List<T>();
			var dirIndex = 0;
			var fCount = 50;
			foreach (var dir in _directories.Where(Directory.Exists)) {
				foreach (var file in Directory.EnumerateFiles(dir)) {
					if (file.Contains(".json")) {
						try {
							var data = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(file));
							if (data != null) {
								if (dirIndex != 0) {
									var id = data.GetValue("Id");
									var name = data.GetValue("Name");
									if (id != null && name != null) {
										if ((int)id == 0 && (string)name! != "Random") {
											data["Id"] = fCount;
										}
									} else {
										continue;
									}
								}

								var obj = data.ToObject<T>();
								if (obj != null) {
									output.Add(obj);
								}
							}
						} catch (Exception e) {
							Log.Warning($"Parse exception for {file}: " + e.Message);
						}
					}

					fCount++;
				}

				dirIndex++;
			}

			return output;
		}

See More Examples