System.IO.Directory.Exists(string)

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

14425 Examples 7

19 View Source File : Form1.cs
License : MIT License
Project Creator : 200Tigersbloxed

void runVerifyCheck()
        {
            if (verifyPermissions(bsl)) { }
            else
            {
                MessageBox.Show("Please run the installer as administrator to continue! (Beat Saber Folder Denied)", "Access Denied to Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            if(Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\Files"))
            {
                if (verifyPermissions(AppDomain.CurrentDomain.BaseDirectory + @"\Files")) { }
                else
                {
                    MessageBox.Show("Please run the installer as administrator to continue! (Installer Folder Denied)", "Access Denied to Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                }
            }
            else
            {
                Directory.CreateDirectory("Files");
                if (verifyPermissions(AppDomain.CurrentDomain.BaseDirectory + @"\Files")) { }
                else
                {
                    MessageBox.Show("Please run the installer as administrator to continue! (Installer Folder Denied)", "Access Denied to Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                }
            }
        }

19 View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : 2881099

public void Build(IDbFirst dbfirst, string templateDirectory, string outputDirectory, params string[] database) {
			if (dbfirst == null) throw new ArgumentException("dbfirst 参数不能为 null");
			if (string.IsNullOrEmpty(templateDirectory) || Directory.Exists(templateDirectory) == false) throw new ArgumentException("templateDirectory 目录不存在");
			if (string.IsNullOrEmpty(templateDirectory)) throw new ArgumentException("outputDirectory 不能为 null");
			if (database == null || database.Any() == false) throw new ArgumentException("database 参数不能为空");
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			templateDirectory = new DirectoryInfo(templateDirectory).FullName;
			outputDirectory = new DirectoryInfo(outputDirectory).FullName;
			if (templateDirectory.IndexOf(outputDirectory, StringComparison.CurrentCultureIgnoreCase) != -1) throw new ArgumentException("outputDirectory 目录不能设置在 templateDirectory 目录内");
			var tables = dbfirst.GetTablesByDatabase(database);
			var tpl = new TemplateEngin(templateDirectory, "FreeSql", "FreeSql.DatabaseModel");
			BuildEachDirectory(templateDirectory, outputDirectory, tpl, dbfirst, tables);
			tpl.Dispose();
		}

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

public async Task DumpAsync(string output)
        {
            // check and create output folder
            var dumpPath = output;
            while (!string.IsNullOrEmpty(dumpPath) && !Directory.Exists(dumpPath))
            {
                var parent = Path.GetDirectoryName(dumpPath);
                if (parent == null || parent == dumpPath)
                    dumpPath = null;
                else
                    dumpPath = parent;
            }
            if (filesystemStructure is null)
                (filesystemStructure, emptyDirStructure) = GetFilesystemStructure();
            var validators = GetValidationInfo();
            if (!string.IsNullOrEmpty(dumpPath))
            {
                var root = Path.GetPathRoot(Path.GetFullPath(output));
                var drive = DriveInfo.GetDrives().FirstOrDefault(d => d?.RootDirectory.FullName.StartsWith(root) ?? false);
                if (drive != null)
                {
                    var spaceAvailable = drive.AvailableFreeSpace;
                    TotalFileSize = filesystemStructure.Sum(f => f.Length);
                    var diff = TotalFileSize + 100 * 1024 - spaceAvailable;
                    if (diff > 0)
                        Log.Warn($"Target drive might require {diff.replacedtorageUnit()} of additional free space");
                }
            }

            foreach (var dir in emptyDirStructure)
                Log.Trace($"Empty dir: {dir}");
            foreach (var file in filesystemStructure)
                Log.Trace($"0x{file.StartSector:x8}: {file.Filename} ({file.Length})");
            var outputPathBase = Path.Combine(output, OutputDir);
            if (!Directory.Exists(outputPathBase))
                Directory.CreateDirectory(outputPathBase);

            TotalFileCount = filesystemStructure.Count;
            TotalSectors = discReader.TotalClusters;
            Log.Debug("Using decryption key: " + allMatchingKeys.First().DecryptedKeyId);
            var decryptionKey = allMatchingKeys.First().DecryptedKey;
            var sectorSize = (int)discReader.ClusterSize;
            var unprotectedRegions = driveStream.GetUnprotectedRegions();
            ValidationStatus = true;

            foreach (var dir in emptyDirStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    var convertedName = Path.DirectorySeparatorChar == '\\' ? dir : dir.Replace('\\', Path.DirectorySeparatorChar);
                    var outputName = Path.Combine(outputPathBase, convertedName);
                    if (!Directory.Exists(outputName))
                    {
                        Log.Debug("Creating empty directory " + outputName);
                        Directory.CreateDirectory(outputName);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((dir, "Unexpected error: " + ex.Message));
                }
            }
            
            foreach (var file in filesystemStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    Log.Info($"Reading {file.Filename} ({file.Length.replacedtorageUnit()})");
                    CurrentFileNumber++;
                    var convertedFilename = Path.DirectorySeparatorChar == '\\' ? file.Filename : file.Filename.Replace('\\', Path.DirectorySeparatorChar);
                    var inputFilename = Path.Combine(input, convertedFilename);

                    if (!File.Exists(inputFilename))
                    {
                        Log.Error($"Missing {file.Filename}");
                        BrokenFiles.Add((file.Filename, "missing"));
                        continue;
                    }

                    var outputFilename = Path.Combine(outputPathBase, convertedFilename);
                    var fileDir = Path.GetDirectoryName(outputFilename);
                    if (!Directory.Exists(fileDir))
                    {
                        Log.Debug("Creating directory " + fileDir);
                        Directory.CreateDirectory(fileDir);
                    }

                    var error = false;
                    var expectedHashes = (
                        from v in validators
                        where v.Files.ContainsKey(file.Filename)
                        select v.Files[file.Filename].Hashes
                    ).ToList();
                    var lastHash = "";
                    var tries = 2;
                    do
                    {
                        try
                        {
                            tries--;
                            using var outputStream = File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
                            using var inputStream = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
                            using var decrypter = new Decrypter(inputStream, driveStream, decryptionKey, file.StartSector, sectorSize, unprotectedRegions);
                            Decrypter = decrypter;
                            await decrypter.CopyToAsync(outputStream, 8 * 1024 * 1024, Cts.Token).ConfigureAwait(false);
                            outputStream.Flush();
                            var resultHashes = decrypter.GetHashes();
                            var resultMd5 = resultHashes["MD5"];
                            if (decrypter.WasEncrypted && decrypter.WasUnprotected)
                                Log.Debug("Partially decrypted " + file.Filename);
                            else if (decrypter.WasEncrypted)
                                Log.Debug("Decrypted " + file.Filename);

                            if (!expectedHashes.Any())
                            {
                                if (ValidationStatus == true)
                                    ValidationStatus = null;
                            }
                            else if (!IsMatch(resultHashes, expectedHashes))
                            {
                                error = true;
                                var msg = "Unexpected hash: " + resultMd5;
                                if (resultMd5 == lastHash || decrypter.LastBlockCorrupted)
                                {
                                    Log.Error(msg);
                                    BrokenFiles.Add((file.Filename, "corrupted"));
                                    break;
                                }
                                Log.Warn(msg + ", retrying");
                            }

                            lastHash = resultMd5;
                        }
                        catch (Exception e)
                        {
                            Log.Error(e, e.Message);
                            error = true;
                        }
                    } while (error && tries > 0 && !Cts.IsCancellationRequested);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((file.Filename, "Unexpected error: " + ex.Message));
                }
            }
            Log.Info("Completed");
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 200Tigersbloxed

private void button1_Click(object sender, EventArgs e)
        {
            // Find the Steam folder
            RegistryKey rk1s = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
            if (rk1s != null)
            {
                RegistryKey rk2 = rk1s.OpenSubKey("Software");
                if (rk2 != null)
                {
                    RegistryKey rk3 = rk2.OpenSubKey("Valve");
                    if (rk3 != null)
                    {
                        RegistryKey rk4 = rk3.OpenSubKey("Steam");
                        if (rk4 != null)
                        {
                            userownssteam = true;
                            string phrase = rk4.GetValue("SteamPath").ToString();
                            steaminstallpath = phrase;
                        }
                    }
                }
            }

            if(userownssteam == false)
            {
                MessageBox.Show("Uh Oh!", "Steam Could not be found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else{
                bsl = steaminstallpath + @"/steamapps/common/Beat Saber";
                if(Directory.Exists(bsl))
                {
                    if(File.Exists(bsl + @"\Beat Saber.exe"))
                    {
                        if(File.Exists(bsl + @"\IPA.exe"))
                        {
                            textBox1.Text = bsl;
                            pictureBox1.Image = BSMulti_Installer2.Properties.Resources.tick;
                            button4.BackColor = SystemColors.MenuHighlight;
                            allownext = true;
                            runVerifyCheck();
                            findMultiplayerVersion();
                        }
                        else
                        {
                            MessageBox.Show("IPA.exe Could not be found! Is Beat Saber Modded?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Beat Saber.exe Could not be found! Is Beat Saber Installed?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Beat Saber Could not be found! Is Beat Saber Installed under Steam?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    bsl = "";
                }
            }
        }

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

private void outputBrowseButton_Click(object sender, EventArgs e)
        {
            var fullPath = Path.GetFullPath(outputTextBox.Text);
            var dialog = new FolderBrowserDialog
            {
                Description = "Select output folder",
                SelectedPath = fullPath,
            };
            var dialogResult = dialog.ShowDialog();
            if (dialogResult != DialogResult.OK || string.IsNullOrEmpty(dialog.SelectedPath) || !Directory.Exists(dialog.SelectedPath))
                return;

            outputTextBox.Text = dialog.SelectedPath;
        }

19 View Source File : CommandLineParser.cs
License : MIT License
Project Creator : 0xd4d

public static JitDasmOptions Parse(string[] args) {
			if (args.Length == 0)
				throw new ShowCommandLineHelpException();

			var options = new JitDasmOptions();
			for (int i = 0; i < args.Length; i++) {
				var arg = args[i];
				var next = i + 1 < args.Length ? args[i + 1] : null;
				switch (arg) {
				case "-h":
				case "--help":
					throw new ShowCommandLineHelpException();

				case "-p":
				case "--pid":
					if (next is null)
						throw new CommandLineParserException("Missing pid value");
					if (!int.TryParse(next, out options.Pid))
						throw new CommandLineParserException($"Invalid pid: {next}");
					try {
						using (var process = Process.GetProcessById(options.Pid))
							VerifyProcess(process);
					}
					catch (ArgumentException) {
						throw new CommandLineParserException($"Process does not exist, pid = {options.Pid}");
					}
					i++;
					break;

				case "-pn":
				case "--process":
					if (next is null)
						throw new CommandLineParserException("Missing process name");
					Process[]? processes = null;
					try {
						processes = Process.GetProcessesByName(next);
						if (processes.Length == 0)
							throw new CommandLineParserException($"Could not find process '{next}'");
						if (processes.Length > 1)
							throw new CommandLineParserException($"Found more than one process with name '{next}'");
						options.Pid = processes[0].Id;
						VerifyProcess(processes[0]);
					}
					finally {
						if (!(processes is null)) {
							foreach (var p in processes)
								p.Dispose();
						}
					}
					i++;
					break;

				case "-m":
				case "--module":
					if (next is null)
						throw new CommandLineParserException("Missing module name");
					options.ModuleName = next;
					i++;
					break;

				case "-l":
				case "--load":
					if (next is null)
						throw new CommandLineParserException("Missing module filename");
					if (!File.Exists(next))
						throw new CommandLineParserException($"Could not find module {next}");
					options.LoadModule = Path.GetFullPath(next);
					i++;
					break;

				case "--no-run-cctor":
					options.RunClreplacedConstructors = false;
					break;

				case "-s":
				case "--search":
					if (next is null)
						throw new CommandLineParserException("Missing replacedembly search path");
					foreach (var path in next.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries)) {
						if (Directory.Exists(path))
							options.replacedemblySearchPaths.Add(path);
					}
					i++;
					break;

				case "--diffable":
					options.Diffable = true;
					break;

				case "--no-addr":
					options.ShowAddresses = false;
					break;

				case "--no-bytes":
					options.ShowHexBytes = false;
					break;

				case "--no-source":
					options.ShowSourceCode = false;
					break;

				case "--heap-search":
					options.HeapSearch = true;
					break;

				case "--filename-format":
					if (next is null)
						throw new CommandLineParserException("Missing filename format");
					switch (next) {
					case "name":
						options.FilenameFormat = FilenameFormat.MemberName;
						break;
					case "tokname":
						options.FilenameFormat = FilenameFormat.TokenMemberName;
						break;
					case "token":
						options.FilenameFormat = FilenameFormat.Token;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename format: {next}");
					}
					i++;
					break;

				case "-f":
				case "--file":
					if (next is null)
						throw new CommandLineParserException("Missing filename kind");
					switch (next) {
					case "stdout":
						options.FileOutputKind = FileOutputKind.Stdout;
						break;
					case "file":
						options.FileOutputKind = FileOutputKind.OneFile;
						break;
					case "type":
						options.FileOutputKind = FileOutputKind.OneFilePerType;
						break;
					case "method":
						options.FileOutputKind = FileOutputKind.OneFilePerMethod;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename kind: {next}");
					}
					i++;
					break;

				case "-d":
				case "--disasm":
					if (next is null)
						throw new CommandLineParserException("Missing disreplacedembler kind");
					switch (next) {
					case "masm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Masm;
						break;
					case "nasm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Nasm;
						break;
					case "gas":
					case "att":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Gas;
						break;
					case "intel":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Intel;
						break;
					default:
						throw new CommandLineParserException($"Unknown disreplacedembler kind: {next}");
					}
					i++;
					break;

				case "-o":
				case "--output":
					if (next is null)
						throw new CommandLineParserException("Missing output file/dir");
					options.OutputDir = next;
					i++;
					break;

				case "--type":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--type-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				case "--method":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--method-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				default:
					throw new CommandLineParserException($"Unknown option: {arg}");
				}
			}

			if (!string2.IsNullOrEmpty(options.LoadModule)) {
				using (var process = Process.GetCurrentProcess())
					options.Pid = process.Id;
				options.ModuleName = options.LoadModule;
			}

			if (string.IsNullOrEmpty(options.ModuleName))
				throw new CommandLineParserException("Missing module name");
			if (options.Pid == 0)
				throw new CommandLineParserException("Missing process id or name");
			if (options.FileOutputKind != FileOutputKind.Stdout && string.IsNullOrEmpty(options.OutputDir))
				throw new CommandLineParserException("Missing output file/dir");
			return options;
		}

19 View Source File : MainForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void init()
        {
            // 创建目录
            if (!Directory.Exists(SESSION_DIR))
            {
                Directory.CreateDirectory(SESSION_DIR);
            }
            if (!Directory.Exists(CONF_DIR))
            {
                Directory.CreateDirectory(CONF_DIR);
            }
            if (!Directory.Exists(HELP_DIR))
            {
                Directory.CreateDirectory(HELP_DIR);
            }
            if (!Directory.Exists(TEMP_DIR))
            {
                Directory.CreateDirectory(TEMP_DIR);
            }            

            // 渲染Session列表
            RenderSessionList();

        }

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

static void Main(string[] args) {
            string inputDir;
            if (args.Length != 1 || !Directory.Exists(inputDir = args[0])) {
                Console.Error.WriteLine("Usage: inputdir");
                return;
            }

            foreach (string path in Directory.GetFiles(inputDir)) {
                Console.WriteLine($"Stripping: {path}");
                Strip(path);
            }
        }

19 View Source File : CodeGenerate.cs
License : MIT License
Project Creator : 2881099

public async Task<string> Setup(Models.TaskBuild task)
        {



            try
            {
                var paths = await Task.Run(() =>
                 {

                     var config = new TemplateServiceConfiguration();
                     config.EncodedStringFactory = new RawStringFactory();
                     var service = RazorEngineService.Create(config);
                     Engine.Razor = service;


                     ///本次要操作的数据库
                     var dataBases = task.TaskBuildInfos.Where(a => a.Level == 1).ToList();

                     string path = string.Empty;

                     foreach (var db in dataBases)
                     {
                         //创建数据库连接
                         using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(db.DataBaseConfig.DataType, db.DataBaseConfig.ConnectionStrings)
                        .Build())
                         {

                             //取指定数据库信息
                             var tables = fsql.DbFirst.GetTablesByDatabase(db.Name);
							 var outputTables = tables;

                             //是否有指定表
                             var uTables = task.TaskBuildInfos.Where(a => a.Level > 1).Select(a => a.Name).ToArray();
                             if (uTables.Length > 0)
                                 //过滤不要的表
                                 outputTables = outputTables.Where(a => uTables.Contains(a.Name)).ToList();

                             //根据用户设置组装生成路径并验证目录是否存在
                             path = $"{task.GeneratePath}\\{db.Name}";
                             if (!Directory.Exists(path))
                                 Directory.CreateDirectory(path);

							 var razorId = Guid.NewGuid().ToString("N");
							 Engine.Razor.Compile(task.Templates.Code, razorId);
                             //开始生成操作
                             foreach (var table in outputTables)
                             {
								 var sw = new StringWriter();
								 var model = new RazorModel(fsql, task, tables, table);
								 Engine.Razor.Run(razorId, sw, null, model);
 

                                 StringBuilder plus = new StringBuilder();
                                 plus.AppendLine("//------------------------------------------------------------------------------");
                                 plus.AppendLine("// <auto-generated>");
                                 plus.AppendLine("//     此代码由工具生成。");
                                 plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                                 plus.AppendLine("//     Website: http://www.freesql.net");
                                 plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                                 plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                                 plus.AppendLine("// </auto-generated>");
                                 plus.AppendLine("//------------------------------------------------------------------------------");

                                 plus.Append(sw.ToString());

                                 plus.AppendLine();
                                 File.WriteAllText($"{path}\\{task.FileName.Replace("{name}", model.GetCsName(table.Name))}", plus.ToString());
                             }
                         }
                     }
                     return path;
                 });

                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                return "生成时发生异常,请检查模版代码.";
            }


        }

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

static bool VerifyFile(out string path, params string[] paths) {
            path = Path.Combine(paths);
            if (!File.Exists(path) && !Directory.Exists(path)) {
                Console.Error.WriteLine($"Missing: {path}");
                return false;
            }
            return true;
        }

19 View Source File : FileUploadProvider.cs
License : MIT License
Project Creator : 17MKH

public async Task<IResultModel<FileDescriptor>> Upload(FileUploadModel model, CancellationToken cancellationToken = default)
    {
        Check.NotNull(model, nameof(model), "file upload model is null");

        Check.NotNull(model.StorageRootDirectory, nameof(model.StorageRootDirectory), "the file storage root directory is null");

        var result = new ResultModel<FileDescriptor>();

        if (model.FormFile == null)
            return result.Failed("请选择文件!");

        var size = model.FormFile.Length;

        //验证文件大小
        if (model.MaxSize > 0 && model.MaxSize < size)
            return result.Failed($"文件大小不能超过{new FileSize(model.MaxSize).ToString()}");

        var name = model.FileName.IsNull() ? model.FormFile.FileName : model.FileName;

        var descriptor = new FileDescriptor(name, size);

        //验证扩展名
        if (model.LimitExtensions != null && !model.LimitExtensions.Any(m => m.EqualsIgnoreCase(descriptor.Extension)))
            return result.Failed($"文件格式无效,请上传{model.LimitExtensions.Aggregate((x, y) => x + "," + y)}格式的文件");

        //按照日期来保存文件
        var date = DateTime.Now;
        descriptor.DirectoryName = Path.Combine(model.StorageRootDirectory, date.ToString("yyyy"), date.ToString("MM"), date.ToString("dd"));

        //创建目录
        if (!Directory.Exists(descriptor.DirectoryName))
        {
            Directory.CreateDirectory(descriptor.DirectoryName);
        }

        //生成文件存储名称
        descriptor.StorageName = $"{Guid.NewGuid().ToString().Replace("-", "")}.{descriptor.Extension}";

        //写入
        await using var stream = new FileStream(descriptor.FullName, FileMode.Create);

        //计算MD5
        if (model.CalculateMd5)
        {
            descriptor.Md5 = _md5Encrypt.Encrypt(stream);
        }

        await model.FormFile.CopyToAsync(stream, cancellationToken);

        return result.Success(descriptor);
    }

19 View Source File : ApplicationBuilderExtensions.cs
License : MIT License
Project Creator : 17MKH

public static IApplicationBuilder UseDefaultPage(this IApplicationBuilder app)
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/app");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        //设置默认文档
        var defaultFilesOptions = new DefaultFilesOptions();
        defaultFilesOptions.DefaultFileNames.Clear();
        defaultFilesOptions.DefaultFileNames.Add("index.html");
        app.UseDefaultFiles(defaultFilesOptions);

        var options = new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(path),
            RequestPath = new PathString("/app")
        };

        app.UseStaticFiles(options);

        var appPath = "app";
        var rewriteOptions = new RewriteOptions().AddRedirect("^$", appPath);

        app.UseRewriter(rewriteOptions);

        return app;
    }

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

private static string EnsureDirectory(string directory, ILogger logger, string dirAlias, bool create)
        {
            if (string.IsNullOrEmpty(directory))
            {
                directory = Directory.GetCurrentDirectory();
                logger.LogDetailed(
                    $"{dirAlias} directory was not specified, so the current directory \"{directory}\" is used as an output one.");
            }
            else if (!Path.IsPathFullyQualified(directory))
            {
                directory = Path.GetFullPath(directory, Directory.GetCurrentDirectory());
                logger.LogDetailed($"{dirAlias} directory is converted to fully qualified \"{directory}\".");
            }


            if (!Directory.Exists(directory))
            {
                if (create)
                {
                    try
                    {
                        Directory.CreateDirectory(directory);
                        logger.LogDetailed($"Directory \"{directory}\" was created.");
                    }
                    catch (Exception e)
                    {
                        throw new SqExpressCodeGenException($"Could not create directory: \"{directory}\".", e);
                    }
                }
                else
                {
                    throw new SqExpressCodeGenException($"\"{directory}\" directory does not exist.");
                }
            }

            return directory;
        }

19 View Source File : Form2.cs
License : MIT License
Project Creator : 200Tigersbloxed

void InstallMultiContinued()
        {
            statuslabel.Text = "Status: Extracting Files";
            progressBar1.Value = 80;
            DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Files");
            foreach (FileInfo file in di.GetFiles())
            {
                string[] splitdot = file.Name.Split('.');
                if (splitdot[1] == "zip")
                {
                    ZipFile.ExtractToDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\" + splitdot[0] + @".zip", @"Files\" + splitdot[0]);
                }
            }
            statuslabel.Text = "Status: Moving Files";
            progressBar1.Value = 90;
            foreach (DirectoryInfo dir in di.GetDirectories())
            {
                if (multiselected == "a")
                {
                    if (dir.Name == "ca")
                    {
                        DirectoryInfo cadi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca");
                        if (Directory.Exists(bsl + @"\CustomAvatars"))
                        {
                            // dont u dare delete someone's custom avatars folder
                        }
                        else
                        {
                            Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\CustomAvatars", bsl + @"\CustomAvatars");
                        }
                        if (Directory.Exists(bsl + @"\DynamicOpenVR"))
                        {
                            Directory.Delete(bsl + @"\DynamicOpenVR", true);
                            Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\DynamicOpenVR", bsl + @"\DynamicOpenVR");
                        }
                        else
                        {
                            Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\DynamicOpenVR", bsl + @"\DynamicOpenVR");
                        }
                        foreach (DirectoryInfo cadir in cadi.GetDirectories())
                        {
                            if (cadir.Name == "Plugins")
                            {
                                // Don't move CustomAvatar's DLL
                            }
                        }
                    }
                }
                if(dir.Name == "dc")
                {
                    DirectoryInfo dcdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dc");
                    foreach (DirectoryInfo dcdir in dcdi.GetDirectories())
                    {
                    if (dcdir.Name == "Plugins")
                    {
                         foreach (FileInfo file in dcdir.GetFiles())
                         {
                            if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
                                    File.Delete(bsl + @"\Plugins\" + file.Name);
                                    File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
                                }
                               else
                                {
                                   File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
                                }
                            }
                         }
                            if (dcdir.Name == "Libs")
                            {
                                foreach (DirectoryInfo dcnativedir in dcdir.GetDirectories())
                                {
                                    if (Directory.Exists(bsl + @"\Libs\Native")) {
                                    Directory.Delete(bsl + @"\Libs\Native", true);
                                    Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\dc\Libs\Native", bsl + @"\Libs\Native");
                                }
                                    else
                                    {
                                        Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\dc\Libs\Native", bsl + @"\Libs\Native");
                                    }
                                }
                            }
                        }
                    }
                    if(dir.Name == "dep")
                    {
                        DirectoryInfo depdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dep\dep");
                        foreach (DirectoryInfo depdir in depdi.GetDirectories())
                        {
                            if (depdir.Name == "Plugins")
                            {
                                foreach (FileInfo file in depdir.GetFiles())
                                {
                                    if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
                                    File.Delete(bsl + @"\Plugins\" + file.Name);
                                    File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
                                }
                                    else
                                    {
                                        File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
                                    }
                                }
                            }
                        }
                    }
                if (multiselected == "a")
                {
                    if (dir.Name == "dovr")
                    {
                        DirectoryInfo dovrdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dovr");
                        foreach (DirectoryInfo dovrdir in dovrdi.GetDirectories())
                        {
                            if (dovrdir.Name == "Plugins")
                            {
                                foreach (FileInfo file in dovrdir.GetFiles())
                                {
                                    if (File.Exists(bsl + @"\Plugins\" + file.Name))
                                    {
                                        File.Delete(bsl + @"\Plugins\" + file.Name);
                                        File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
                                    }
                                    else
                                    {
                                        File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
                                    }
                                }
                            }
                            if (dovrdir.Name == "Libs")
                            {
                                foreach (FileInfo file in dovrdir.GetFiles())
                                {
                                    if (File.Exists(bsl + @"\Libs\" + file.Name))
                                    {
                                        File.Delete(bsl + @"\Libs\" + file.Name);
                                        File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
                                    }
                                    else
                                    {
                                        File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
                                    }
                                }
                            }
                        }
                    }
                }
                    if (dir.Name == "multiplayer")
                    {
                        DirectoryInfo multiplayerdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\multiplayer");
                        foreach (DirectoryInfo multiplayerdir in multiplayerdi.GetDirectories())
                        {
                            if (multiplayerdir.Name == "Plugins")
                            {
                                foreach (FileInfo file in multiplayerdir.GetFiles())
                                {
                                    if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
                                    File.Delete(bsl + @"\Plugins\" + file.Name);
                                    File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
                                }
                                    else
                                    {
                                        File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
                                    }
                                }
                            }
                            if (multiplayerdir.Name == "Libs")
                            {
                                foreach (FileInfo file in multiplayerdir.GetFiles())
                                {
                                    if (File.Exists(bsl + @"\Libs\" + file.Name)) {
                                    File.Delete(bsl + @"\Libs\" + file.Name);
                                    File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
                                }
                                    else
                                    {
                                        File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
                                    }  
                                }
                            }
                        }
                    }
                }
            if(multiselected == "a")
            {
                if (File.Exists(@"Files\CustomAvatar.dll"))
                {
                    if (File.Exists(bsl + @"\Plugins\CustomAvatar.dll"))
                    {
                        File.Delete(bsl + @"\Plugins\CustomAvatar.dll");
                        File.Move(@"Files\CustomAvatar.dll", bsl + @"\Plugins\CustomAvatar.dll");
                    }
                    else
                    {
                        File.Move(@"Files\CustomAvatar.dll", bsl + @"\Plugins\CustomAvatar.dll");
                    }
                }
            }
                
                statuslabel.Text = "Status: Complete!";
            progressBar1.Value = 100;
            allowinstalluninstall = true;
                currentlyinstallinguninstalling = false;
                button3.BackColor = SystemColors.MenuHighlight;
                button4.BackColor = SystemColors.MenuHighlight;
                DialogResult dialogResult = MessageBox.Show("Multiplayer is installed! Would you like to exit?", "Complete!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    Application.Exit();
                }
        }

19 View Source File : CelesteNetEmojiComponent.cs
License : MIT License
Project Creator : 0x0ade

public void Handle(CelesteNetConnection con, DataNetEmoji netemoji) {
            Logger.Log(LogLevel.VVV, "netemoji", $"Received {netemoji.ID}");

            string dir = Path.Combine(Path.GetTempPath(), "CelesteNetClientEmojiCache");
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            string path = Path.Combine(dir, $"{netemoji.ID}-{netemoji.GetHashCode():X8}.png");
            using (FileStream fs = File.OpenWrite(path))
            using (MemoryStream ms = new(netemoji.Data))
                ms.CopyTo(fs);

            RunOnMainThread(() => {
                Logger.Log(LogLevel.VVV, "netemoji", $"Registering {netemoji.ID}");

                bool registered = false;

                try {
                    VirtualTexture vt = VirtualContent.CreateTexture(path);
                    MTexture mt = new(vt);
                    if (vt.Texture_Safe == null) // Needed to trigger lazy loading.
                        throw new Exception($"Couldn't load emoji {netemoji.ID}");

                    Registered.Add(netemoji.ID);
                    RegisteredFiles.Add(path);
                    Emoji.Register(netemoji.ID, mt);
                    Emoji.Fill(CelesteNetClientFont.Font);
                    registered = true;

                } finally {
                    if (!registered)
                        File.Delete(path);
                }
            });
        }

19 View Source File : IceDeployVersionForm.cs
License : Apache License 2.0
Project Creator : 214175590

void stb_local_pdir_TextChanged(object sender, EventArgs e)
        {
            string dir = stb_local_pdir.Text;
            string path = stb_icexml.Text;
            if (!string.IsNullOrWhiteSpace(dir) && string.IsNullOrWhiteSpace(path))
            {
                if (Directory.Exists(dir))
                {
                    dir = dir.Replace("\\", "/");
                    if(!dir.EndsWith("/")){
                        dir += "/";
                    }
                    path = string.Format("{0}icedeploy/config/{1}.xml", dir, ice.AppName);
                    if (File.Exists(path))
                    {
                        stb_icexml.Text = path;
                    }
                }
            }            
        }

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

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            ProductCode = ProductCode?.ToUpperInvariant();
            var result = new HashSet<DiscKeyInfo>();
            var knownFilenames = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
            Log.Trace("Searching local cache for a match...");
            if (Directory.Exists(discKeyCachePath))
            {
                var matchingIrdFiles = Directory.GetFiles(discKeyCachePath, "*.ird", SearchOption.TopDirectoryOnly);
                foreach (var irdFile in matchingIrdFiles)
                {
                    try
                    {
                        try
                        {
                            var ird = IrdParser.Parse(File.ReadAllBytes(irdFile));
                            result.Add(new DiscKeyInfo(ird.Data1, null, irdFile, KeyType.Ird, ird.Crc32.ToString("x8")));
                            knownFilenames.Add(Path.GetFileName(irdFile));
                        }
                        catch (InvalidDataException)
                        {
                            File.Delete(irdFile);
                            continue;
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e);
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Warn(e, e.Message);
                    }
                }
            }

            Log.Trace("Searching IRD Library for match...");
            var irdInfoList = await Client.SearchAsync(ProductCode, cancellationToken).ConfigureAwait(false);
            var irdList = irdInfoList?.Data?.Where(
                              i => !knownFilenames.Contains(i.Filename) && i.Filename.Substring(0, 9).ToUpperInvariant() == ProductCode
                          ).ToList() ?? new List<SearchResulreplacedem>(0);
            if (irdList.Count == 0)
                Log.Debug("No matching IRD file was found in the Library");
            else
            {
                Log.Info($"Found {irdList.Count} new match{(irdList.Count == 1 ? "" : "es")} in the IRD Library");
                foreach (var irdInfo in irdList)
                {
                    var ird = await Client.DownloadAsync(irdInfo, discKeyCachePath, cancellationToken).ConfigureAwait(false);
                    result.Add(new DiscKeyInfo(ird.Data1, null, Path.Combine(discKeyCachePath, irdInfo.Filename), KeyType.Ird, ird.Crc32.ToString("x8")));
                    knownFilenames.Add(irdInfo.Filename);
                }
            }
            if (knownFilenames.Count == 0)
            {
                Log.Warn("No valid matching IRD file could be found");
                Log.Info($"If you have matching IRD file, you can put it in '{discKeyCachePath}' and try dumping the disc again");
            }

            Log.Info($"Found {result.Count} IRD files");
            return result;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 2401dem

private void button4_Click(object sender, EventArgs e)
        {
            if (IsFolder)
                if (textBox2.Text != "" && Directory.Exists(textBox2.Text))
                    System.Diagnostics.Process.Start(textBox2.Text);
                else
                    MessageBox.Show("Output folder does not exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
                if (textBox2.Text.LastIndexOf('\\') != -1 && Directory.Exists(textBox2.Text.Substring(0, textBox2.Text.LastIndexOf('\\'))))
                System.Diagnostics.Process.Start(textBox2.Text.Substring(0, textBox2.Text.LastIndexOf('\\')));
            else
                MessageBox.Show("Output folder does not exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public override T[] LoadAll<T>() {
            lock (GlobalLock) {
                if (!Directory.Exists(UserRoot))
                    return Dummy<T>.EmptyArray;
                string name = GetDataFileName(typeof(T));
                return Directory.GetDirectories(UserRoot).Select(dir => LoadRaw<T>(Path.Combine(dir, name))).ToArray();
            }
        }

19 View Source File : StaticFiles.cs
License : MIT License
Project Creator : 2881099

public static IApplicationBuilder UseFreeAdminLteStaticFiles(this IApplicationBuilder app, string requestPathBase) {
			if (_isStaticFiles == false) {
				lock (_isStaticFilesLock) {
					if (_isStaticFiles == false) {
						var curPath = AppDomain.CurrentDomain.BaseDirectory;
						var zipPath = $"{curPath}/{Guid.NewGuid()}.zip";
						using (var zip = WwwrootStream()) {
							using (var fs = File.Open(zipPath, FileMode.OpenOrCreate)) {
								zip.CopyTo(fs);
								fs.Close();
							}
							zip.Close();
						}
						var wwwrootPath = Path.Combine(curPath, "FreeSql.AdminLTE.wwwroot");
						if (Directory.Exists(wwwrootPath)) Directory.Delete(wwwrootPath, true);
						try {
							System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, wwwrootPath, Encoding.UTF8);
						} catch (Exception ex) {
							throw new Exception($"UseFreeAdminLtePreview 错误,资源文件解压失败:{ex.Message}", ex);
						} finally {
							File.Delete(zipPath);
						}

						app.UseStaticFiles(new StaticFileOptions {
							RequestPath = requestPathBase.TrimEnd('/'),
							FileProvider = new PhysicalFileProvider(wwwrootPath)
						});

						_isStaticFiles = true;
					}
				}
			}

			return app;
		}

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

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

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

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            var result = new HashSet<DiscKeyInfo>();
            try
            {
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
                if (embeddedResources.Any())
                    Log.Trace("Loading embedded redump keys");
                else
                    Log.Warn("No embedded redump keys found");
                foreach (var res in embeddedResources)
                {
                    using var resStream = replacedembly.GetManifestResourceStream(res);
                    using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
                    foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
                                                                    || e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        using var keyStream = zipEntry.Open();
                        using var memStream = new MemoryStream();
                        await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
                        var discKey = memStream.ToArray();
                        if (zipEntry.Length > 256/8*2)
                        {
                            Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
                            continue;
                        }
                        if (discKey.Length > 16)
                        {
                            discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                        }

                        try
                        {
                            result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, $"Invalid disc key format: {discKey}");
                        }
                    }
                }
                if (result.Any())
                    Log.Info($"Found {result.Count} embedded redump keys");
                else
                    Log.Warn($"Failed to load any embedded redump keys");
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed to load embedded redump keys");
            }

            Log.Trace("Loading cached redump keys");
            var diff = result.Count;
            try
            {
                if (Directory.Exists(discKeyCachePath))
                {
                    var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
                        .Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
                    foreach (var dkeyFile in matchingDiskKeys)
                    {
                        try
                        {
                            try
                            {
                                var discKey = File.ReadAllBytes(dkeyFile);
                                if (discKey.Length > 16)
                                {
                                    try
                                    {
                                        discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                                    }
                                    catch (Exception e)
                                    {
                                        Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
                                    }
                                }
                                result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
                            }
                            catch (InvalidDataException)
                            {
                                File.Delete(dkeyFile);
                                continue;
                            }
                            catch (Exception e)
                            {
                                Log.Warn(e);
                                continue;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, e.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex, "Failed to load redump keys from local cache");
            }
            diff = result.Count - diff;
            Log.Info($"Found {diff} cached disc keys");
            return result;
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public override string[] GetAll()
            => !Directory.Exists(UserRoot) ? Dummy<string>.EmptyArray : Directory.GetDirectories(UserRoot).Select(name => Path.GetFileName(name)).ToArray();

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

private void irdButton_Click(object sender, EventArgs e)
        {
            var fullPath = Path.GetFullPath(irdTextBox.Text);
            var dialog = new FolderBrowserDialog
            {
                Description = "Select IRD cache folder",
                SelectedPath = fullPath,
            };
            var dialogResult = dialog.ShowDialog();
            if (dialogResult != DialogResult.OK || string.IsNullOrEmpty(dialog.SelectedPath) || !Directory.Exists(dialog.SelectedPath))
                return;

            irdTextBox.Text = dialog.SelectedPath;
        }

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

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

19 View Source File : ModuleCollection.cs
License : MIT License
Project Creator : 17MKH

public void Load()
    {
        var modulesRootPath = Path.Combine(AppContext.BaseDirectory, Constants.ROOT_DIR);
        if (!Directory.Exists(modulesRootPath))
            return;

        var moduleDirs = Directory.GetDirectories(modulesRootPath);
        if (!moduleDirs.Any())
            return;

        _replacedemblyHelper = new replacedemblyHelper();
        var optionsList = new List<ModuleOptions>();
        foreach (var dir in moduleDirs)
        {
            var code = Path.GetFileName(dir)!.Split("_")[1];
            var options = _configuration.Get<ModuleOptions>($"Mkh:Modules:{code}");
            if (options.Db != null)
            {
                options.Code = code;
                options.Dir = dir;
                optionsList.Add(options);
            }
        }

        foreach (var options in optionsList.OrderBy(m => m.Sort))
        {
            LoadModule(options);
        }

        //释放资源
        _replacedemblyHelper = null;
    }

19 View Source File : ServiceCollectionExtensions.cs
License : MIT License
Project Creator : 17MKH

public static IServiceCollection AddData(this IServiceCollection services, IModuleCollection modules)
    {
        foreach (var module in modules)
        {
            var dbOptions = module.Options!.Db;
            var dbContextType = module.Layerreplacedemblies.Core.GetTypes().FirstOrDefault(m => typeof(DbContext).IsreplacedignableFrom(m));

            var dbBuilder = services.AddMkhDb(dbContextType, opt =>
            {
                opt.Provider = dbOptions.Provider;

                //Sqlite数据库自动创建数据库文件
                if (dbOptions.ConnectionString.IsNull() && dbOptions.Provider == DbProvider.Sqlite)
                {
                    string dbFilePath = Path.Combine(AppContext.BaseDirectory, "db");
                    if (!Directory.Exists(dbFilePath))
                    {
                        Directory.CreateDirectory(dbFilePath);
                    }

                    dbOptions.ConnectionString = $"Data Source={dbFilePath}/{module.Code}.db;Mode=ReadWriteCreate";
                }

                opt.ConnectionString = dbOptions.ConnectionString;
                opt.Log = dbOptions.Log;
                opt.TableNamePrefix = dbOptions.TableNamePrefix;
                opt.TableNameSeparator = dbOptions.TableNameSeparator;
                opt.Version = dbOptions.Version;
            });

            //加载仓储
            dbBuilder.AddRepositoriesFromreplacedembly(module.Layerreplacedemblies.Core);

            //启用代码优先
            if (dbOptions.CodeFirst)
            {
                dbBuilder.AddCodeFirst(opt =>
                {
                    opt.CreateDatabase = dbOptions.CreateDatabase;
                    opt.UpdateColumn = dbOptions.UpdateColumn;
                    opt.InitData = dbOptions.InitData;
                    opt.InitDataFilePath = module.DbInitFilePath;
                });
            }

            //特性事务
            foreach (var dic in module.ApplicationServices)
            {
                dbBuilder.AddTransactionAttribute(dic.Key, dic.Value);
            }

            dbBuilder.Build();
        }

        return services;
    }

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

public bool DirectoryExists(string path)
        {
            return Directory.Exists(path);
        }

19 View Source File : GeneratorOptionsSerializer.cs
License : MIT License
Project Creator : 188867052

public string Save(string directory)
        {
            if (string.IsNullOrWhiteSpace(directory))
            {
                directory = Environment.CurrentDirectory;
            }

            if (!Directory.Exists(directory))
            {
                this.logger.LogTrace($"Creating Directory: {directory}");
                Directory.CreateDirectory(directory);
            }

            return string.Empty;
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

private void InsertFileRaw(string path, Stream stream) {
            lock (GlobalLock) {
                string? dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                if (File.Exists(path))
                    File.Delete(path);
                Stream target = File.OpenWrite(path);
                stream.CopyTo(target);
            }
        }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : 214175590

public static void CopyDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
                return;

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

            string[] files = Directory.GetFiles(fromDir);
            foreach (string formFileName in files)
            {
                string fileName = Path.GetFileName(formFileName);
                string toFileName = Path.Combine(toDir, fileName);
                File.Copy(formFileName, toFileName);
            }
            string[] fromDirs = Directory.GetDirectories(fromDir);
            foreach (string fromDirName in fromDirs)
            {
                string dirName = Path.GetFileName(fromDirName);
                string toDirName = Path.Combine(toDir, dirName);
                CopyDir(fromDirName, toDirName);
            }
        }

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

public static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Path to \"SqExpress\" project folder should be specified as the first argument");
                return 1;
            }

            string projDir = args[0];

            if (!Directory.Exists(projDir))
            {
                Console.WriteLine($"Directory \"{projDir}\" does not exist");
                return 2;
            }


            IReadOnlyList<NodeModel> buffer;
            try
            {
                buffer = BuildModelRoslyn(projDir);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Could not build model: {e.Message}");
                return 3;
            }

            try
            {
                Generate(projDir, @"SyntaxTreeOperations\ExprDeserializer.cs", buffer, GenerateDeserializer);
                Generate(projDir, @"SyntaxTreeOperations\Internal\ExprModifier.cs", buffer, GenerateModifier);
                Generate(projDir, @"SyntaxTreeOperations\Internal\ExprWalker.cs", buffer, GenerateWalker);
                Generate(projDir, @"SyntaxTreeOperations\Internal\ExprWalkerPull.cs", buffer, GenerateWalkerPull);
                Generate(projDir, @"SyntaxModifyExtensions.cs", buffer, GenerateSyntaxModify);
                Console.WriteLine("Done!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return 4;
            }

            return 0;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 200Tigersbloxed

private void button2_Click(object sender, EventArgs e)
        {
            //Find the Oculus Folder
            RegistryKey rk1s = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
            if (rk1s != null)
            {
                RegistryKey rk2 = rk1s.OpenSubKey("Software");
                if (rk2 != null)
                {
                    RegistryKey rk3 = rk2.OpenSubKey("WOW6432Node");
                    if (rk3 != null)
                    {
                        RegistryKey rk4 = rk3.OpenSubKey("Oculus VR, LLC");
                        if (rk4 != null)
                        {
                            RegistryKey rk5 = rk4.OpenSubKey("Oculus");
                            if(rk5 != null)
                            {
                                RegistryKey rk6 = rk5.OpenSubKey("Config");
                                if(rk6 != null)
                                {
                                    userownsoculus = true;
                                    string phrase = rk6.GetValue("InitialAppLibrary").ToString();
                                    oculusinstallpath = phrase;
                                }
                            }
                        }
                    }
                }
            }

            if (userownsoculus == false)
            {
                MessageBox.Show("Oculus Could not be found!", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                bsl = oculusinstallpath + @"/Software/Software/hyperbolic-magnetism-beat-saber";
                if (Directory.Exists(bsl))
                {
                    if (File.Exists(bsl + @"\Beat Saber.exe"))
                    {
                        if (File.Exists(bsl + @"\IPA.exe"))
                        {
                            textBox1.Text = bsl;
                            pictureBox1.Image = BSMulti_Installer2.Properties.Resources.tick;
                            button4.BackColor = SystemColors.MenuHighlight;
                            allownext = true;
                            runVerifyCheck();
                            findMultiplayerVersion();
                        }
                        else
                        {
                            MessageBox.Show("IPA.exe Could not be found! Is Beat Saber Modded?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Beat Saber.exe Could not be found! Is Beat Saber Installed?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Beat Saber Could not be found! Is Beat Saber Installed under Oculus?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    bsl = "";
                }
            }
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public override Stream WriteFile(string uid, string name) {
            string path = GetUserFilePath(uid, name);
            string? dir = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            if (File.Exists(path))
                File.Delete(path);
            return File.OpenWrite(path);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2401dem

public static int Denoise()
        {
            if (_is_folder)
            {
                if (Directory.Exists(_input_path) || Directory.Exists(_input_path.Substring(0, _input_path.LastIndexOf('\\') > 0 ? _input_path.LastIndexOf('\\') : 0)))
                {
                    if (Directory.Exists(_output_path) || Directory.Exists(_output_path.Substring(0, _output_path.LastIndexOf('\\') > 0 ? _output_path.LastIndexOf('\\') : 0)))
                    {
                        var file_paths = Directory.GetFiles(_input_path, "*.*", SearchOption.TopDirectoryOnly);
                        List<string> input_file_paths = new List<string>();
                        List<string> output_file_paths = new List<string>();
                        foreach (string file_path in file_paths)
                        {
                            Regex regex = new Regex(".\\.(bmp|jpg|png|tif|exr)$", RegexOptions.IgnoreCase);
                            if (regex.IsMatch(file_path))
                            {
                                input_file_paths.Add(file_path);
                                output_file_paths.Add(_output_path + "\\out_" + file_path.Substring(file_path.LastIndexOf('\\') + 1));
                                Console.WriteLine(file_path);
                            }
                        }
                        int width = _getWidth(input_file_paths[0].ToCharArray());
                        int height = _getHeight(input_file_paths[0].ToCharArray());

                        if (width == -1 || height == -1)
                        {
                            MessageBox.Show("Picture Format Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Program.form1.unlockButton();
                            return -1;
                        }
                        //Bitmap pBuffer = new Bitmap(input_file_paths[0], false);
                        IntPtr tmpptr = new IntPtr();

                        _jobStart(width, height, _blend);
                        for (int i = 0; i < input_file_paths.Count; ++i)
                        {
                            Program.form1.SetProgress((float)i / (float)input_file_paths.Count);
                            if (File.Exists(output_file_paths[i]))
                                continue;
                            //IntPtr tmpptr = 
                            tmpptr = _denoiseImplement(input_file_paths[i].ToCharArray(), output_file_paths[i].ToCharArray(), _blend, _is_folder);
                            /*if (tmpptr != null)
                                if (Program.form1.DrawToPictureBox(tmpptr, pBuffer.Width, pBuffer.Height) == 0)
                                    continue;
                                else
                                {
                                    MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    break;
                                }
                            else
                            {
                                //MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                //break;
                            }*/
                        }

                        _jobComplete();
                        if (tmpptr != null)
                            if (Program.form1.DrawToPictureBox(tmpptr, width, height) != 0)
                                MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        Program.form1.SetProgress(1.0f);
                        Program.form1.unlockButton();
                        return 0;
                    }
                    else
                        MessageBox.Show("Output folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("Input folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (File.Exists(_input_path))
                {
                    if (Directory.Exists(_output_path.Substring(0, _output_path.LastIndexOf('\\'))))
                    {
                        int width = _getWidth(_input_path.ToCharArray());
                        int height = _getHeight(_input_path.ToCharArray());
                        Console.WriteLine(width.ToString());
                        Console.WriteLine(height.ToString());
                        if (width == -1 || height == -1)
                        {
                            MessageBox.Show("Picture Format Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Program.form1.unlockButton();
                            return -1;
                        }

                        _jobStart(width, height, _blend);
                        IntPtr tmpptr = _denoiseImplement(_input_path.ToCharArray(), _output_path.ToCharArray(), _blend, _is_folder);
                        if (tmpptr != null)
                        {
                            if (Program.form1.DrawToPictureBox(tmpptr, width, height) == -1)
                                MessageBox.Show("Picture Size Error(NULL to Draw)!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                            MessageBox.Show("Picture Size Error!(NULL Return)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Program.form1.SetProgress(1.0f);
                        Program.form1.unlockButton();
                        _jobComplete();
                        return 0;
                    }
                    else
                        MessageBox.Show("Output folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("Input file does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Program.form1.unlockButton();
            return -1;
        }

19 View Source File : Chromium.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3

private static List<string> GetAllProfiles(string DirectoryPath)
        {
            List<string> loginDataFiles = new List<string>
            {
                DirectoryPath + @"\Default\Login Data",
                DirectoryPath + @"\Login Data"
            }; 

            if (Directory.Exists(DirectoryPath))
            {
                foreach (string dir in Directory.GetDirectories(DirectoryPath))
                {
                    if (dir.Contains("Profile"))
                        loginDataFiles.Add(dir + @"\Login Data");
                }
            }

            return loginDataFiles;
        }

19 View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void CentralServerConfigForm_Load(object sender, EventArgs e)
        {
            if(monitorForm != null){
                this.Text = "Docker公共配置 - " + monitorForm.getSessionConfig().Host;
                cfgDir = MainForm.TEMP_DIR + monitorForm.getSessionConfig().Host;
                cfgDir = cfgDir.Replace("\\", "/");
                if (!Directory.Exists(cfgDir))
                {
                    Directory.CreateDirectory(cfgDir);
                }

                string cfgPath = monitorForm.getSessionConfig().CentralServerConfigDir;
                if (string.IsNullOrWhiteSpace(cfgPath))
                {
                    string home = monitorForm.getSftp().getHome();
                    if (!home.EndsWith("/"))
                    {
                        home += "/";
                    }
                    remoteCfgPath = home + "docker/central-server-config";
                    monitorForm.getSessionConfig().CentralServerConfigDir = remoteCfgPath;
                    AppConfig.Instance.SaveConfig(2);
                }
                else
                {
                    remoteCfgPath = cfgPath;
                }                

                stb_remote_dir.Text = remoteCfgPath;

                LoadRemoteYmls();
            }
            else
            {
                btn_reload.Enabled = false;
                btn_show.Enabled = false;
                下载到本地ToolStripMenuItem.Enabled = false;
                上传到服务器ToolStripMenuItem.Enabled = false;
                更改文件名ToolStripMenuItem.Enabled = false;
                删除文件ToolStripMenuItem.Enabled = false;
                this.AllowDrop = true;
            }
        }

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

public static string ChangePath(string path, char separator) {
            // Can't trust File.Exists if MONO_IOMAP_ALL is set.
            if (!MONO_IOMAP_ALL) {
                string pathMaybe = path;
                // Check if target exists in the first place.
                if (Directory.Exists(path) || File.Exists(path))
                    return pathMaybe;

                // Try a simpler fix first: Maybe the casing is already correct...
                pathMaybe = path.Replace('/', separator).Replace('\\', separator);
                if (Directory.Exists(pathMaybe) || File.Exists(pathMaybe))
                    return pathMaybe;

                // Fall back to the slow rebuild.
            }

            // Check if the path has been rebuilt before.
            Dictionary<string, string> cachedPaths;
            if (!_CachedChanges.TryGetValue(separator, out cachedPaths))
                _CachedChanges[separator] = cachedPaths = new Dictionary<string, string>();
            string cachedPath;
            if (cachedPaths.TryGetValue(path, out cachedPath))
                return cachedPath;

            // Split and rebuild path.

            string[] pathSplit = path.Split(DirectorySeparatorChars);

            StringBuilder builder = new StringBuilder();

            bool unixRooted = false;

            if (Path.IsPathRooted(path)) {
                // The first element in a rooted path will always be correct.
                // On Windows, this will be the drive letter.
                // On Unix and Unix-like systems, this will be empty.
                if (unixRooted = (builder.Length == 0))
                    // Path is rooted, but the path separator is the root.
                    builder.Append(separator);
                else
                    builder.Append(pathSplit[0]);
            }

            for (int i = 1; i < pathSplit.Length; i++) {
                string next;
                if (i < pathSplit.Length - 1)
                    next = GetDirectory(builder.ToString(), pathSplit[i]);
                else
                    next = GetTarget(builder.ToString(), pathSplit[i]);
                next = next ?? pathSplit[i];

                if (i != 1 || !unixRooted)
                    builder.Append(separator);

                builder.Append(next);
            }

            return cachedPaths[path] = builder.ToString();
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 2401dem

private void button1_Click(object sender, EventArgs e)
        {
            if (IsFolder)
            {
                CommonOpenFileDialog dialog = new CommonOpenFileDialog();
                dialog.IsFolderPicker = true;


                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    string tmp = dialog.FileName;
                    if (tmp.LastIndexOf('\\') != -1)
                    {
                        textBox1.Text = tmp;
                        if (!Directory.Exists(textBox2.Text))
                            textBox2.Text = tmp;
                    }
                }

            }
            else
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Filter = "Supported Files (*.bmp, *.jpg, *.png, *.tif, *.exr)|*.jpg;*.png;*.bmp;*.tif;*.exr|Bitmap Images (*.bmp)|*.bmp|JPEG Images (*.jpg)|*.jpg|PNG Images (*.png)|*.png|TIFF Images (*.tif)|*.tif|OpenEXR Images (*.exr)|*.exr";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string tmp = dialog.FileName;
                    if (tmp.LastIndexOf('\\') != -1)
                    {
                        textBox1.Text = tmp;
                        textBox2.Text = tmp.Substring(0, tmp.LastIndexOf('\\') + 1) + "out_" + tmp.Substring(tmp.LastIndexOf('\\') + 1);
                    }
                }
            }
        }

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

public async Task<Ird> DownloadAsync(SearchResulreplacedem irdInfo, string localCachePath, CancellationToken cancellationToken)
        {
            Ird result = null;
            try
            {
                var localCacheFilename = Path.Combine(localCachePath, irdInfo.Filename);
                // first we search local cache and try to load whatever data we can
                try
                {
                    if (File.Exists(localCacheFilename))
                        return IrdParser.Parse(File.ReadAllBytes(localCacheFilename));
                }
                catch (Exception e)
                {
                    Log.Warn(e, "Error accessing local IRD cache: " + e.Message);
                }
                try
                {
                    var resultBytes = await client.GetByteArrayAsync(GetDownloadLink(irdInfo.Filename)).ConfigureAwait(false);
                    result = IrdParser.Parse(resultBytes);
                    try
                    {
                        if (!Directory.Exists(localCachePath))
                            Directory.CreateDirectory(localCachePath);
                        File.WriteAllBytes(localCacheFilename, resultBytes);
                    }
                    catch (Exception ex)
                    {
                        Log.Warn(ex, $"Failed to write {irdInfo.Filename} to local cache: {ex.Message}");
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(e, $"Failed to download {irdInfo.Filename}: {e.Message}");
                }
                return result;
            }
            catch (Exception e)
            {
                Log.Error(e);
                return result;
            }
        }

19 View Source File : IceDeployVersionForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void button1_Click(object sender, EventArgs e)
        {
            string name = btn_start.Text;
            if (name == "重置状态")
            {
                btn_start.Text = "开始部署";
                errorLabel.Text = "";
                pb_state1.BackgroundImage = Properties.Resources.Circle_72px0;
                l_state1.BackColor = backColor0;
                line_state1.BackColor = backColor0;
                pb_state2.BackgroundImage = Properties.Resources.Circle_72px0;
                l_state2.BackColor = backColor0;
                line_state2.BackColor = backColor0;
                pb_state3.BackgroundImage = Properties.Resources.Circle_72px0;
                l_state3.BackColor = backColor0;
                line_state3.BackColor = backColor0;
                pb_state4.BackgroundImage = Properties.Resources.Circle_72px0;
                l_state4.BackColor = backColor0;
                return;
            }

            // 开始部署
            string local_pdir = stb_local_pdir.Text;
            string xml = stb_icexml.Text;
            string remote_pdir = stb_remote_pdir.Text;
            string mvnxml = stb_maven_xml.Text;
            if (string.IsNullOrWhiteSpace(local_pdir))
            {
                MessageBox.Show(this, "请选择本地代码目录");
                return;
            }
            if (!Directory.Exists(local_pdir))
            {
                MessageBox.Show(this, "本地代码目录不存在,请检查");
                return;
            }
            if (checkBox1.Checked && string.IsNullOrWhiteSpace(local_pdir))
            {
                MessageBox.Show(this, "请选择ice接口服务配置文件(" + ice.AppName + ".xml)");
                return;
            }
            if (string.IsNullOrWhiteSpace(remote_pdir))
            {
                MessageBox.Show(this, "请输入服务器ICE项目目录");
                return;
            }
            if (checkBox2.Checked && string.IsNullOrWhiteSpace(mvnxml))
            {
                MessageBox.Show(this, "自动打包需要配置Maven环境变量,并指定settings.xml");
                return;
            }

            if (ice.Project == null)
            {
                ice.Project = new IceProjectAttr();
            }
            ice.Project.LocalCodePath = local_pdir;
            ice.Project.LocalIceXmlPath = xml;
            ice.Project.MavenSetting = mvnxml;
            AppConfig.Instance.SaveConfig(2);

            // 开始
            run = true;
            timer1.Start();
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public void SaveRaw<T>(string path, T data) where T : notnull {
            lock (GlobalLock) {
                string? dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                using (Stream stream = File.OpenWrite(path + ".tmp"))
                using (StreamWriter writer = new(stream))
                    YamlHelper.Serializer.Serialize(writer, data, typeof(T));

                if (File.Exists(path))
                    File.Delete(path);
                File.Move(path + ".tmp", path);
            }
        }

19 View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : 2881099

void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			var files = Directory.GetFiles(templateDirectory);
			foreach (var file in files) {
				var fi = new FileInfo(file);
				if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
					var outputExtension = "." + fi.Name.Split('.')[1];
					if (fi.Name.StartsWith("for-table.")) {
						foreach (var table in tables) {
							var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
							if (result.EndsWith("return;")) continue;
							var outputName = table.Name + outputExtension;
							var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
							if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
							var outputStream = Encoding.UTF8.GetBytes(result);
							var fullname = outputDirectory + "/" + outputName;
							if (File.Exists(fullname)) File.Delete(fullname);
							using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
								outfs.Write(outputStream, 0, outputStream.Length);
								outfs.Close();
							}
						}
						continue;
					} else {
						var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
						var outputName = fi.Name;
						var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
						if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
						var outputStream = Encoding.UTF8.GetBytes(result);
						var fullname = outputDirectory + "/" + outputName;
						if (File.Exists(fullname)) File.Delete(fullname);
						using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
							outfs.Write(outputStream, 0, outputStream.Length);
							outfs.Close();
						}
					}
				}
				File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
			}
			var dirs = Directory.GetDirectories(templateDirectory);
			foreach(var dir in dirs) {
				BuildEachDirectory(dir, outputDirectory +  dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
			}
		}

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

private void startDumpingButton_Click(object sender, EventArgs e)
        {
            var outputDir = Path.Combine(settings.OutputDir, currentDumper.OutputDir);
            if (Directory.Exists(outputDir))
            {
                var msgResult = MessageBox.Show(
                    $"Output folder ({currentDumper.OutputDir}) already exists.\n" +
                    "Are you sure you want to overwrite any existing files?",
                    "Output folder check",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning
                );
                if (msgResult == DialogResult.No)
                    return;
            }

            settingsButton.Enabled = false;
            startDumpingButton.Enabled = false;
            startDumpingButton.Visible = false;
            step3StatusLabel.Text = "⏳";
            step3Label.Text = "Decrypting and copying files...";


            discBackgroundWorker.DoWork += DumpDisc;
            discBackgroundWorker.RunWorkerCompleted += DumpDiscFinished;
            discBackgroundWorker.ProgressChanged += DiscDumpUpdateProgress;
            discBackgroundWorker.RunWorkerAsync(currentDumper);

            cancelDiscDumpButton.Enabled = true;
            cancelDiscDumpButton.Visible = true;
            dumpingProgressBar.Visible = true;
            dumpingProgressLabel.Text = "replacedyzing file structure...";
            dumpingProgressLabel.Visible = true;
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal, Handle);
        }

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

static void Main(string[] args) {
            // Required for the relative extra paths to work properly.
            if (!File.Exists("MonoMod.RuntimeDetour.dll"))
                Environment.CurrentDirectory = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

            string inputDir, outputDir;
            if (args.Length != 2 ||
                !Directory.Exists(inputDir = args[0]) ||
                !Directory.Exists(outputDir = args[1])) {
                Console.Error.WriteLine("Usage: inputdir outputdir");
                return;
            }

            // Check that the files exist.
            if (!VerifyFile(out string inputXNA, inputDir, "Terraria.XNA.exe"))
                return;
            if (!VerifyFile(out string inputFNA, inputDir, "Terraria.FNA.exe"))
                return;

            // Strip or copy.
            foreach (string path in Directory.GetFiles(inputDir)) {
                if (!path.EndsWith(".exe") && !path.EndsWith(".dll")) {
                    Console.WriteLine($"Copying: {path}");
                    File.Copy(path, Path.Combine(outputDir, Path.GetFileName(path)));
                    continue;
                }

                Console.WriteLine($"Stripping: {path}");
                Stripper.Strip(path);
            }

            // Generate hooks.
            string hooksXNA = Path.Combine(outputDir, "Windows.Pre.dll");
            string hooksFNA = Path.Combine(outputDir, "Mono.Pre.dll");
            GenHooks(inputXNA, hooksXNA);
            GenHooks(inputFNA, hooksFNA);

            // Merge generated .dlls and MonoMod into one .dll per environment.
            string[] extrasMod = {
                "TerrariaHooks.dll",
                "MonoMod.exe",
                "MonoMod.RuntimeDetour.dll",
                "MonoMod.Utils.dll"
            };
            Repack(hooksXNA, extrasMod, Path.Combine(outputDir, "Windows.dll"), "TerrariaHooks.dll");
            File.Delete(hooksXNA);
            Repack(hooksFNA, extrasMod, Path.Combine(outputDir, "Mono.dll"), "TerrariaHooks.dll");
            File.Delete(hooksFNA);
        }

19 View Source File : CelesteNetServerModule.cs
License : MIT License
Project Creator : 0x0ade

public virtual void Save(string path = "") {
            path = Path.GetFullPath(path.Nullify() ?? FilePath);

            Logger.Log(LogLevel.INF, "settings", $"Saving {GetType().Name} to {path}");

            string? dir = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            using (Stream stream = File.OpenWrite(path + ".tmp"))
            using (StreamWriter writer = new(stream))
                Save(writer);

            if (File.Exists(path))
                File.Delete(path);
            File.Move(path + ".tmp", path);
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public void DeleteRawAll(string path) {
            lock (GlobalLock) {
                if (Directory.Exists(path))
                    Directory.Delete(path, true);
            }
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public override void CopyTo(UserData other) {
            using UserDataBatchContext batch = other.OpenBatch();
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);

                Dictionary<string, Type?> types = new();
                replacedembly[] asms = AppDomain.CurrentDomain.Getreplacedemblies();

                foreach (string uid in GetAll()) {
                    PrivateUserInfo info = Load<PrivateUserInfo>(uid);
                    other.Insert(uid, info.Key, info.KeyFull, !info.KeyFull.IsNullOrEmpty());

                    foreach (string path in Directory.GetFiles(Path.Combine(UserRoot, uid))) {
                        string name = Path.GetFileNameWithoutExtension(path);
                        if (name == typeof(PrivateUserInfo).FullName)
                            continue;

                        if (!types.TryGetValue(name, out Type? type)) {
                            foreach (replacedembly asm in asms)
                                if ((type = asm.GetType(name)) != null)
                                    break;
                            types[name] = type;
                        }

                        using Stream stream = File.OpenRead(path);
                        other.InsertData(uid, name, type, stream);
                    }

                    string dir = Path.Combine(UserRoot, uid, "data");
                    if (Directory.Exists(dir)) {
                        foreach (string path in Directory.GetFiles(dir)) {
                            string name = Path.GetFileName(path);
                            using Stream stream = File.OpenRead(path);
                            other.InsertFile(uid, name, stream);
                        }
                    }
                }
            }
        }

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

public void RestoreBackup(string root) {
            string origRoot = Path.Combine(root, "orig");
            // Check for an "orig" folder to restore any backups from
            if (!Directory.Exists(origRoot))
                return;
            RestoreBackup(root, origRoot);
        }

19 View Source File : ConfigurationHelper.cs
License : MIT License
Project Creator : 17MKH

public IConfiguration Load(string configFileName, string environmentName = "", bool reloadOnChange = false)
    {
        var filePath = Path.Combine(AppContext.BaseDirectory, "config");
        if (!Directory.Exists(filePath))
            return null;

        var builder = new ConfigurationBuilder()
            .SetBasePath(filePath)
            .AddJsonFile(configFileName.ToLower() + ".json", true, reloadOnChange);

        if (environmentName.NotNull())
        {
            builder.AddJsonFile(configFileName.ToLower() + "." + environmentName + ".json", true, reloadOnChange);
        }

        return builder.Build();
    }

See More Examples