System.IO.DirectoryInfo.Create()

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

758 Examples 7

19 Source : CoreCmsUserTocashController.cs
with Apache License 2.0
from CoreUnion

[HttpPost]
        [Description("选择导出")]
        public async Task<JsonResult> SelectExportExcel([FromBody] FMArrayIntIds enreplacedy)
        {
            var jm = new AdminUiCallBack();

            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var sheet1 = book.CreateSheet("Sheet1");
            //获取list数据
            var listmodel = await _coreCmsUserTocashServices.QueryListByClauseAsync(p => enreplacedy.id.Contains(p.id),
                p => p.id, OrderByType.Asc);
            //给sheet1添加第一行的头部标题
            var row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("ID号");
            row1.CreateCell(1).SetCellValue("用户ID");
            row1.CreateCell(2).SetCellValue("提现金额");
            row1.CreateCell(3).SetCellValue("银行名称");
            row1.CreateCell(4).SetCellValue("银行缩写");
            row1.CreateCell(5).SetCellValue("账号地区ID");
            row1.CreateCell(6).SetCellValue("开户行");
            row1.CreateCell(7).SetCellValue("账户名");
            row1.CreateCell(8).SetCellValue("卡号");
            row1.CreateCell(9).SetCellValue("提现服务费");
            row1.CreateCell(10).SetCellValue("提现状态");
            row1.CreateCell(11).SetCellValue("创建时间");
            row1.CreateCell(12).SetCellValue("更新时间");

            //将数据逐步写入sheet1各个行
            for (var i = 0; i < listmodel.Count; i++)
            {
                var rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(listmodel[i].id.ToString());
                rowtemp.CreateCell(1).SetCellValue(listmodel[i].userId.ToString());
                rowtemp.CreateCell(2).SetCellValue(listmodel[i].money.ToString());
                rowtemp.CreateCell(3).SetCellValue(listmodel[i].bankName);
                rowtemp.CreateCell(4).SetCellValue(listmodel[i].bankCode);
                rowtemp.CreateCell(5).SetCellValue(listmodel[i].bankAreaId.ToString());
                rowtemp.CreateCell(6).SetCellValue(listmodel[i].accountBank);
                rowtemp.CreateCell(7).SetCellValue(listmodel[i].accountName);
                rowtemp.CreateCell(8).SetCellValue(listmodel[i].cardNumber);
                rowtemp.CreateCell(9).SetCellValue(listmodel[i].withdrawals.ToString());
                rowtemp.CreateCell(10).SetCellValue(listmodel[i].status.ToString());
                rowtemp.CreateCell(11).SetCellValue(listmodel[i].createTime.ToString());
                rowtemp.CreateCell(12).SetCellValue(listmodel[i].updateTime.ToString());
            }

            // 导出excel
            var webRootPath = _webHostEnvironment.WebRootPath;
            var tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-CoreCmsUserTocash导出(选择结果).xls";
            var filePath = webRootPath + tpath;
            var di = new DirectoryInfo(filePath);
            if (!di.Exists) di.Create();
            var fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return Json(jm);
        }

19 Source : LegacyForgeInstaller.cs
with MIT License
from Corona-Studio

public async Task<ForgeInstallResult> InstallForgeTaskAsync()
        {
            if (string.IsNullOrEmpty(ForgeExecutablePath))
                throw new ArgumentNullException("未指定\"ForgeExecutablePath\"参数");
            if (string.IsNullOrEmpty(RootPath))
                throw new ArgumentNullException("未指定\"RootPath\"参数");

            try
            {
                InvokeStatusChangedEvent("解压安装文件", 0.05);

                using var reader = ArchiveFactory.Open(ForgeExecutablePath);
                var profileEntry =
                    reader.Entries.FirstOrDefault(e => e.Key.Equals("install_profile.json", StringComparison.Ordinal));
                var legacyJarEntry =
                    reader.Entries.FirstOrDefault(e =>
                        e.Key.Equals($"forge-{ForgeVersion}-universal.jar", StringComparison.OrdinalIgnoreCase));

                if (profileEntry == default)
                    return new ForgeInstallResult
                    {
                        Error = new ErrorModel
                        {
                            Cause = "未找到 install_profile.json",
                            Error = "未找到 install_profile.json",
                            ErrorMessage = "未找到 install_profile.json"
                        },
                        Succeeded = false
                    };

                if (legacyJarEntry == default)
                    return new ForgeInstallResult
                    {
                        Error = new ErrorModel
                        {
                            Cause = "未找到 Forge Jar",
                            Error = "未找到 Forge Jar",
                            ErrorMessage = "未找到 Forge Jar"
                        },
                        Succeeded = false
                    };

                InvokeStatusChangedEvent("解压完成", 0.1);

                await using var stream = profileEntry.OpenEntryStream();
                using var sR = new StreamReader(stream, Encoding.UTF8);
                var content = await sR.ReadToEndAsync();

                InvokeStatusChangedEvent("解析安装文档", 0.35);
                var profileModel = JsonConvert.DeserializeObject<LegacyForgeInstallProfile>(content);
                InvokeStatusChangedEvent("解析完成", 0.75);

                var id = string.IsNullOrEmpty(CustomId) ? profileModel.VersionInfo.Id : CustomId;

                var installDir = Path.Combine(RootPath, GamePathHelper.GetGamePath(id));
                var jsonPath = GamePathHelper.GetGameJsonPath(RootPath, id);

                var forgeDi = new DirectoryInfo(installDir);
                if (!forgeDi.Exists)
                    forgeDi.Create();

                profileModel.VersionInfo.Id = id;

                var forgeLibrary = profileModel.VersionInfo.Libraries.First(l =>
                    l.Name.StartsWith("net.minecraftforge:forge", StringComparison.OrdinalIgnoreCase));
                var mavenInfo = forgeLibrary.Name.ResolveMavenString();

                var libSubPath = GamePathHelper.GetLibraryPath(mavenInfo.Path).Replace('/', '\\');
                var forgeLibPath = Path.Combine(RootPath, libSubPath);

                var libDi = new DirectoryInfo(Path.GetDirectoryName(forgeLibPath));

                if (!libDi.Exists)
                    libDi.Create();

                await using var fs = File.OpenWrite(forgeLibPath);
                legacyJarEntry.WriteTo(fs);

                var versionJsonString = JsonConvert.SerializeObject(profileModel.VersionInfo,
                    JsonHelper.CamelCasePropertyNamesSettings);

                await File.WriteAllTextAsync(jsonPath, versionJsonString);
                InvokeStatusChangedEvent("文件写入完成", 1);

                return new ForgeInstallResult
                {
                    Succeeded = true
                };
            }
            catch (Exception ex)
            {
                return new ForgeInstallResult
                {
                    Error = new ErrorModel
                    {
                        Error = "安装失败",
                        Exception = ex
                    },
                    Succeeded = false
                };
            }
        }

19 Source : CurseForgeInstaller.cs
with MIT License
from Corona-Studio

public async Task InstallTaskAsync()
        {
            InvokeStatusChangedEvent("开始安装", 0);

            var manifest = await ReadManifestTask();
            var idPath = Path.Combine(RootPath, GamePathHelper.GetGamePath(GameId));
            var downloadPath = Path.Combine(Path.GetFullPath(idPath), "mods");

            var di = new DirectoryInfo(downloadPath);

            if (!di.Exists)
                di.Create();

            _needToDownload = manifest.Files.Count;

            var urlBlock = new TransformManyBlock<IEnumerable<CurseForgeFileModel>, ValueTuple<long, long>>(urls =>
            {
                return urls.Select(file => (file.ProjectId, file.FileId));
            });

            var urlBags = new ConcurrentBag<DownloadFile>();
            var actionBlock = new ActionBlock<ValueTuple<long, long>>(async t =>
            {
                var downloadUrlRes = await CurseForgeAPIHelper.GetAddonDownloadUrl(t.Item1, t.Item2);
                var d = downloadUrlRes.Trim('"');
                var fn = Path.GetFileName(d);

                urlBags.Add(new DownloadFile
                {
                    Completed = WhenCompleted,
                    DownloadPath = di.FullName,
                    DownloadUri = d,
                    FileName = fn
                });

                _totalDownloaded++;

                var progress = (double)_totalDownloaded / _needToDownload * 100;

                InvokeStatusChangedEvent($"成功解析 MOD [{t.Item1}] 的下载地址",
                    progress);
            }, new ExecutionDataflowBlockOptions
            {
                BoundedCapacity = 32,
                MaxDegreeOfParallelism = 32
            });

            var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };
            urlBlock.LinkTo(actionBlock, linkOptions);
            urlBlock.Post(manifest.Files);
            urlBlock.Complete();

            await actionBlock.Completion;

            _totalDownloaded = 0;
            var isModAllDownloaded = await DownloadFiles(urlBags);

            if (!isModAllDownloaded)
                throw new NullReferenceException("未能下载全部的 Mods");

            using var archive = ArchiveFactory.Open(Path.GetFullPath(ModPackPath));

            _totalDownloaded = 0;
            _needToDownload = archive.Entries.Count();

            foreach (var entry in archive.Entries)
            {
                if (!entry.Key.StartsWith(manifest.Overrides, StringComparison.OrdinalIgnoreCase)) continue;

                var subPath = entry.Key[(manifest.Overrides.Length + 1)..].Replace('/', '\\');
                if (string.IsNullOrEmpty(subPath)) continue;

                var path = Path.Combine(Path.GetFullPath(idPath), subPath);
                var dirPath = Path.GetDirectoryName(path);

                if (!Directory.Exists(dirPath))
                    Directory.CreateDirectory(dirPath);
                if (entry.IsDirectory)
                {
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    continue;
                }

                var subPathLength = subPath.Length;
                var subPathName = subPathLength > 35
                ? $"...{subPath[(subPathLength - 15)..]}"
                : subPath;

                InvokeStatusChangedEvent($"解压缩安装文件:{subPathName}", (double)_totalDownloaded / _needToDownload * 100);

                await using var fs = File.OpenWrite(path);
                entry.WriteTo(fs);

                _totalDownloaded++;
            }

            InvokeStatusChangedEvent("安装完成", 100);
        }

19 Source : HighVersionForgeInstaller.cs
with MIT License
from Corona-Studio

public async Task<ForgeInstallResult> InstallForgeTaskAsync()
        {
            if (string.IsNullOrEmpty(ForgeExecutablePath))
                throw new ArgumentNullException("未指定\"ForgeExecutablePath\"参数");
            if (string.IsNullOrEmpty(JavaExecutablePath))
                throw new ArgumentNullException("未指定\"JavaExecutablePath\"参数");

            if (!File.Exists(JavaExecutablePath))
                return new ForgeInstallResult
                {
                    Succeeded = false,
                    Error = new ErrorModel
                    {
                        Cause = "找不到Java可执行文件",
                        Error = "Headless安装工具安装前准备失败",
                        ErrorMessage = "找不到Java可执行文件,请确认您的路径是否正确"
                    }
                };

            if (!File.Exists(ForgeExecutablePath))
                return new ForgeInstallResult
                {
                    Succeeded = false,
                    Error = new ErrorModel
                    {
                        Cause = "找不到Forge可执行文件",
                        Error = "安装前准备失败",
                        ErrorMessage = "找不到Forge可执行文件,请确认您的路径是否正确"
                    }
                };

            using var archive = ArchiveFactory.Open(Path.GetFullPath(ForgeExecutablePath));

            #region 解析 Version.json

            InvokeStatusChangedEvent("解析 Version.json", 0.1);

            var versionJsonEntry =
                archive.Entries.FirstOrDefault(e => e.Key.Equals("version.json", StringComparison.OrdinalIgnoreCase));

            if (versionJsonEntry == default)
                return new ForgeInstallResult
                {
                    Succeeded = false,
                    Error = new ErrorModel
                    {
                        Cause = "损坏的 Forge 可执行文件",
                        Error = "安装前准备失败",
                        ErrorMessage = "损坏的 Forge 可执行文件,请确认您的路径是否正确"
                    }
                };

            await using var stream = versionJsonEntry.OpenEntryStream();
            using var sr = new StreamReader(stream, Encoding.UTF8);
            var versionJsonContent = await sr.ReadToEndAsync();
            var versionJsonModel = JsonConvert.DeserializeObject<RawVersionModel>(versionJsonContent);

            var forgeVersion = versionJsonModel.Id.Replace("-forge-", "-");
            var id = string.IsNullOrEmpty(CustomId) ? versionJsonModel.Id : CustomId;

            versionJsonModel.Id = id;

            var jsonPath = GamePathHelper.GetGameJsonPath(RootPath, id);
            var jsonContent = JsonConvert.SerializeObject(versionJsonModel,
                JsonHelper.CamelCasePropertyNamesSettings);

            await File.WriteAllTextAsync(jsonPath, jsonContent);

            #endregion

            #region 解析 Install_profile.json

            InvokeStatusChangedEvent("解析 Install_profile.json", 0.2);

            var installProfileEntry =
                archive.Entries.FirstOrDefault(e =>
                    e.Key.Equals("install_profile.json", StringComparison.OrdinalIgnoreCase));

            await using var ipStream = installProfileEntry.OpenEntryStream();
            using var ipSr = new StreamReader(ipStream, Encoding.UTF8);
            var ipContent = await ipSr.ReadToEndAsync();
            var ipModel = JsonConvert.DeserializeObject<ForgeInstallProfile>(ipContent);

            #endregion

            #region 解析 Lzma

            InvokeStatusChangedEvent("解析 Lzma", 0.4);

            var serverLzma = archive.Entries.FirstOrDefault(e =>
                e.Key.Equals("data/server.lzma", StringComparison.OrdinalIgnoreCase));
            var clientLzma = archive.Entries.FirstOrDefault(e =>
                e.Key.Equals("data/client.lzma", StringComparison.OrdinalIgnoreCase));

            if (serverLzma != default)
            {
                var serverMaven = $"net.minecraftforge:forge:{forgeVersion}:serverdata@lzma";

                ipModel.Data["BINPATCH"].Server = $"[{serverMaven}]";

                var serverBinMaven = serverMaven.ResolveMavenString();
                var serverBinPath = Path.Combine(RootPath,
                    GamePathHelper.GetLibraryPath(serverBinMaven.Path.Replace('/', '\\')));

                var di = new DirectoryInfo(Path.GetDirectoryName(serverBinPath));

                if (!di.Exists)
                    di.Create();

                await using var sFs = File.OpenWrite(serverBinPath);

                serverLzma.WriteTo(sFs);
            }

            if (clientLzma != default)
            {
                var clientMaven = $"net.minecraftforge:forge:{forgeVersion}:clientdata@lzma";

                ipModel.Data["BINPATCH"].Client = $"[{clientMaven}]";

                var clientBinMaven = clientMaven.ResolveMavenString();
                var clientBinPath = Path.Combine(RootPath,
                    GamePathHelper.GetLibraryPath(clientBinMaven.Path.Replace('/', '\\')));

                var di = new DirectoryInfo(Path.GetDirectoryName(clientBinPath));

                if (!di.Exists)
                    di.Create();

                await using var cFs = File.OpenWrite(clientBinPath);
                clientLzma.WriteTo(cFs);
            }

            #endregion

            #region 解压 Forge Jar

            InvokeStatusChangedEvent("解压 Forge Jar", 0.5);

            var forgeJar = archive.Entries.FirstOrDefault(e =>
                e.Key.Equals($"maven/net/minecraftforge/forge/{forgeVersion}/forge-{forgeVersion}.jar",
                    StringComparison.OrdinalIgnoreCase));
            var forgeUniversalJar = archive.Entries.FirstOrDefault(e =>
                e.Key.Equals($"maven/net/minecraftforge/forge/{forgeVersion}/forge-{forgeVersion}-universal.jar",
                    StringComparison.OrdinalIgnoreCase));

            if (forgeJar != default)
            {
                if (forgeUniversalJar != default)
                {
                    var forgeUniversalSubPath = forgeUniversalJar?.Key[(forgeUniversalJar.Key.IndexOf('/') + 1)..];
                    var forgeUniversalLibPath = Path.Combine(RootPath,
                        GamePathHelper.GetLibraryPath(forgeUniversalSubPath?.Replace('/', '\\')));

                    if (string.IsNullOrEmpty(forgeUniversalSubPath)
                        || string.IsNullOrEmpty(forgeUniversalLibPath))
                        return new ForgeInstallResult
                        {
                            Error = new ErrorModel
                            {
                                ErrorMessage = "不支持的格式"
                            },
                            Succeeded = false
                        };

                    var forgeUniversalLibDir = Path.GetDirectoryName(forgeUniversalLibPath);
                    if (!Directory.Exists(forgeUniversalLibDir))
                        Directory.CreateDirectory(forgeUniversalLibDir);

                    await using var forgeUniversalFs = File.OpenWrite(forgeUniversalLibPath);
                    forgeUniversalJar.WriteTo(forgeUniversalFs);
                }

                var forgeSubPath = forgeJar.Key[(forgeJar.Key.IndexOf('/') + 1)..];
                var forgeLibPath =
                    Path.Combine(RootPath, GamePathHelper.GetLibraryPath(forgeSubPath.Replace('/', '\\')));

                var forgeLibDir = Path.GetDirectoryName(forgeLibPath);
                if (!Directory.Exists(forgeLibDir))
                    Directory.CreateDirectory(forgeLibDir);

                await using var forgeFs = File.OpenWrite(forgeLibPath);

                var fLDi = new DirectoryInfo(Path.GetDirectoryName(forgeLibPath));

                if (!fLDi.Exists)
                    fLDi.Create();

                forgeJar.WriteTo(forgeFs);
            }

            #endregion

            #region 解析 Processor

            InvokeStatusChangedEvent("解析 Processor", 1);

            var pathRegex = new Regex("^\\[.+\\]$");
            var variableRegex = new Regex("^{.+}$");

            string ResolvePathRegex(string val)
            {
                if (string.IsNullOrEmpty(val) || string.IsNullOrEmpty(pathRegex.Match(val).Value)) return val;

                var name = val[1..^1];
                var maven = name.ResolveMavenString();
                var path = Path.Combine(RootPath,
                    GamePathHelper.GetLibraryPath(maven.Path.Replace('/', '\\')).Replace('/', '\\'));

                return path;
            }

            var variables = new Dictionary<string, ForgeInstallProfileData>
            {
                {
                    "MINECRAFT_JAR",
                    new ForgeInstallProfileData
                    {
                        Client = GamePathHelper.GetVersionJar(RootPath, MineCraftVersionId)
                    }
                }
            };

            foreach (var (k, v) in ipModel.Data)
                variables.TryAdd(k, new ForgeInstallProfileData
                {
                    Client = ResolvePathRegex(v.Client),
                    Server = ResolvePathRegex(v.Server)
                });

            string ResolveVariableRegex(string val)
            {
                if (string.IsNullOrEmpty(val) || string.IsNullOrEmpty(variableRegex.Match(val).Value)) return val;

                var key = val[1..^1];
                return variables[key].Client;
            }

            var procList = new List<ForgeInstallProcessorModel>();
            var argsReplaceList = new Dictionary<string, string>
            {
                { "{SIDE}", "client" },
                { "{MINECRAFT_JAR}", GamePathHelper.GetVersionJar(RootPath, MineCraftVersionId) },
                { "{MINECRAFT_VERSION}", MineCraftVersion },
                { "{ROOT}", RootPath },
                { "{INSTALLER}", ForgeExecutablePath },
                { "{LIBRARY_DIR}", Path.Combine(RootPath, GamePathHelper.GetLibraryRootPath()) }
            };

            foreach (var proc in ipModel.Processors)
            {
                if (proc.Sides != null &&
                    proc.Sides.Any() &&
                    !proc.Sides.Any(s => s.Equals("client", StringComparison.OrdinalIgnoreCase))
                )
                    continue;

                var outputs = new Dictionary<string, string>();

                if (proc.Outputs?.Any() ?? false)
                    foreach (var (k, v) in proc.Outputs)
                        outputs.TryAdd(ResolveVariableRegex(k), ResolveVariableRegex(v));

                var args = proc.Arguments
                    .Select(arg => StringHelper.ReplaceByDic(arg, argsReplaceList))
                    .Select(ResolvePathRegex)
                    .Select(ResolveVariableRegex)
                    .ToList();
                var model = new ForgeInstallProcessorModel
                {
                    Processor = proc,
                    Arguments = args,
                    Outputs = outputs
                };

                procList.Add(model);
            }

            #endregion

            #region 补全 Libraries

            var libs = ipModel.Libraries;
            libs.AddRange(versionJsonModel.Libraries);

            var resolvedLibs = VersionLocator.GetNatives(libs).Item2;
            var libDownloadInfo = new List<DownloadFile>();

            var hasDownloadFailed = false;

            var retryCount = 0;
            var failedFiles = new ConcurrentBag<DownloadFile>();
            foreach (var lib in resolvedLibs)
            {
                if (
                    lib.Name.StartsWith("net.minecraftforge:forge", StringComparison.OrdinalIgnoreCase) &&
                    string.IsNullOrEmpty(lib.Url)
                )
                    continue;

                var symbolIndex = lib.Path.LastIndexOf('/');
                var fileName = lib.Path[(symbolIndex + 1)..];
                var path = Path.Combine(RootPath,
                    GamePathHelper.GetLibraryPath(lib.Path[..symbolIndex].Replace('/', '\\')));

                /*
                if (!string.IsNullOrEmpty(DownloadUrlRoot))
                {
                    var urlRoot = HttpHelper.RegexMatchUri(lib.Url);
                    var url = lib.Url.Replace($"{urlRoot}/", string.Empty);
                    if (!url.StartsWith("maven", StringComparison.OrdinalIgnoreCase))
                        url = "maven/" + url;

                    lib.Url = $"{DownloadUrlRoot}{url}";
                }
                */

                var libDi = new DirectoryInfo(path);

                if (!libDi.Exists)
                    libDi.Create();

                var df = new DownloadFile
                {
                    Completed = WhenCompleted,
                    CheckSum = lib.Sha1,
                    DownloadPath = path,
                    FileName = fileName,
                    DownloadUri = lib.Url,
                    FileSize = lib.Size
                };

                libDownloadInfo.Add(df);
            }

            _needToDownload = libDownloadInfo.Count;

            await DownloadFiles(libDownloadInfo);

            hasDownloadFailed = !failedFiles.IsEmpty;
            if (hasDownloadFailed)
                return new ForgeInstallResult
                {
                    Succeeded = false,
                    Error = new ErrorModel
                    {
                        Cause = "未能下载全部依赖",
                        Error = "未能下载全部依赖",
                        ErrorMessage = "未能下载全部依赖"
                    }
                };

            #endregion

            #region 启动 Process

            _needToProcess = procList.Count;
            foreach (var processor in procList)
            {
                var maven = processor.Processor.Jar.ResolveMavenString();
                var libPath = Path.Combine(RootPath, GamePathHelper.GetLibraryPath(maven.Path.Replace('/', '\\')));

                using var libArchive = ArchiveFactory.Open(Path.GetFullPath(libPath));
                var libEntry =
                    libArchive.Entries.FirstOrDefault(e =>
                        e.Key.Equals("META-INF/MANIFEST.MF", StringComparison.OrdinalIgnoreCase));

                await using var libStream = libEntry.OpenEntryStream();
                using var libSr = new StreamReader(libStream, Encoding.UTF8);
                var content = await libSr.ReadToEndAsync();
                var mainClreplaced =
                    (from line in content.Split('\n')
                        select line.Split(": ")
                        into lineSp
                        where lineSp[0].Equals("Main-Clreplaced", StringComparison.OrdinalIgnoreCase)
                        select lineSp[1].Trim()).First();

                var totalLibs = processor.Processor.ClreplacedPath;
                totalLibs.Add(processor.Processor.Jar);

                var cp = totalLibs.Select(MavenHelper.ResolveMavenString)
                    .Select(m => Path.Combine(RootPath, GamePathHelper.GetLibraryPath(m.Path).Replace('/', '\\')));
                var cpStr = string.Join(';', cp);
                var parameter = new List<string>
                {
                    "-cp",
                    $"\"{cpStr}\"",
                    mainClreplaced
                };

                parameter.AddRange(processor.Arguments);

                var pi = new ProcessStartInfo(JavaExecutablePath)
                {
                    Arguments = string.Join(' ', parameter),
                    UseShellExecute = false,
                    WorkingDirectory = Path.GetFullPath(RootPath),
                    RedirectStandardError = true,
                    RedirectStandardOutput = true
                };

                using var p = Process.Start(pi);
                var logSb = new StringBuilder();
                var errSb = new StringBuilder();

                p.OutputDataReceived += (_, args) =>
                {
                    if (string.IsNullOrEmpty(args.Data)) return;

                    logSb.AppendLine(args.Data);

                    var data = args.Data ?? string.Empty;
                    var progress = (double)_totalProcessed / _needToProcess;
                    var dataLength = data.Length;
                    var dataStr = dataLength > 30
                                    ? $"..{data[(dataLength - 30)..]}"
                                    : data;

                    InvokeStatusChangedEvent($"{dataStr} <安装信息> ( {_totalProcessed} / {_needToProcess} )", progress);
                };

                p.ErrorDataReceived += (_, args) =>
                {
                    if (string.IsNullOrEmpty(args.Data)) return;

                    errSb.AppendLine(args.Data);

                    var data = args.Data ?? string.Empty;
                    var progress = (double)_totalProcessed / _needToProcess;
                    var dataLength = data.Length;
                    var dataStr = dataLength > 30
                                    ? $"{data[(dataLength - 30)..]}"
                                    : data;


                    InvokeStatusChangedEvent($"{data} <错误> ( {_totalProcessed} / {_needToProcess} )", progress);
                };

                p.BeginOutputReadLine();
                p.BeginErrorReadLine();

                _totalProcessed++;
                await p.WaitForExitAsync();

                var installLogPath = Path.Combine(RootPath, GamePathHelper.GetGamePath(id));

                if (logSb.Length != 0)
                    await File.WriteAllTextAsync(Path.Combine(installLogPath, $"PROCESSOR #{_totalProcessed}_Logs.log"),
                        logSb.ToString());
                if (errSb.Length != 0)
                    await File.WriteAllTextAsync(
                        Path.Combine(installLogPath, $"PROCESSOR #{_totalProcessed}_Errors.log"), errSb.ToString());

                if (errSb.Length != 0)
                    return new ForgeInstallResult
                    {
                        Error = new ErrorModel
                        {
                            Cause = "执行 Forge 安装脚本时出现了错误",
                            Error = errSb.ToString(),
                            ErrorMessage = "安装过程中出现了错误"
                        },
                        Succeeded = false
                    };
            }

            #endregion

            return new ForgeInstallResult
            {
                Succeeded = true
            };
        }

19 Source : FabricInstaller.cs
with MIT License
from Corona-Studio

public async Task<string> InstallTaskAsync()
        {
            InvokeStatusChangedEvent("开始安装", 0);

            var jsonUrl = "https://fabricmc.net/download/technic/?intermediary="
                          + Uri.EscapeDataString(LoaderArtifact.Intermediary.Version)
                          + "&loader="
                          + Uri.EscapeDataString(LoaderArtifact.Loader.Version);
            var jsonContentRes = await HttpHelper.Get(jsonUrl);
            var jsonContent = await jsonContentRes.Content.ReadreplacedtringAsync();
            var versionModel = JsonConvert.DeserializeObject<RawVersionModel>(jsonContent);
            var id = string.IsNullOrEmpty(CustomId)
                ? $"{LoaderArtifact.Loader.GameVersion}-fabric-{LoaderArtifact.Loader.Version}-{LoaderArtifact.Intermediary.Version}"
                : CustomId;

            versionModel.Id = id;
            versionModel.InheritsFrom = LoaderArtifact.Loader.GameVersion;

            InvokeStatusChangedEvent("解析 Libraries 完成", 23.3333);

            var dir = Path.Combine(RootPath, GamePathHelper.GetGamePath(id));
            var di = new DirectoryInfo(dir);

            if (!di.Exists)
                di.Create();
            else
                DirectoryHelper.CleanDirectory(di.FullName);

            var resultJson = JsonConvert.SerializeObject(versionModel, JsonHelper.CamelCasePropertyNamesSettings);
            InvokeStatusChangedEvent("生成版本总成", 70);
            var jsonPath = GamePathHelper.GetGameJsonPath(RootPath, id);

            InvokeStatusChangedEvent("将版本 Json 写入文件", 90);

            await File.WriteAllTextAsync(jsonPath, resultJson);

            InvokeStatusChangedEvent("安装完成", 100);

            return id;
        }

19 Source : LiteLoaderInstaller.cs
with MIT License
from Corona-Studio

public async Task<string> InstallTaskAsync()
        {
            if (InheritVersion == null)
                throw new NullReferenceException("InheritVersion 不能为 null");
            if (VersionModel == null)
                throw new NullReferenceException("VersionModel 不能为 null");

            InvokeStatusChangedEvent("开始安装 LiteLoader", 0);

            var vl = new DefaultVersionLocator(RootPath, Guid.Empty);
            var rawVersion = vl.ParseRawVersion(VersionModel.McVersion);

            InvokeStatusChangedEvent("解析版本", 10);

            if (rawVersion == null)
                throw new UnknownGameNameException(VersionModel.McVersion);

            if (rawVersion.Id != VersionModel.McVersion)
                throw new NotSupportedException("LiteLoader 并不支持这个 MineCraft 版本");

            var id = string.IsNullOrEmpty(CustomId)
                ? $"{VersionModel.McVersion}-LiteLoader{VersionModel.McVersion}-{VersionModel.Version}"
                : CustomId;

            var timeStamp = long.TryParse(VersionModel.Build.Timestamp, out var timeResult) ? timeResult : 0;
            var time = TimeHelper.Unix11ToDateTime(timeStamp);

            InvokeStatusChangedEvent("解析 Libraries", 30);

            var libraries = new List<Library>
            {
                new()
                {
                    Name = $"com.mumfrey:liteloader:{VersionModel.Version}",
                    Url = VersionModel.Type.Equals("SNAPSHOT", StringComparison.OrdinalIgnoreCase)
                        ? SnapshotRoot
                        : ReleaseRoot
                }
            };

            foreach (var lib in VersionModel.Build.Libraries
                .Where(lib => !string.IsNullOrEmpty(lib.Name) && string.IsNullOrEmpty(lib.Url)).Where(lib =>
                    lib.Name.StartsWith("org.ow2.asm", StringComparison.OrdinalIgnoreCase)))
                lib.Url = "https://files.minecraftforge.net/maven/";

            libraries.AddRange(VersionModel.Build.Libraries);

            InvokeStatusChangedEvent("Libraries 解析完成", 60);

            const string mainClreplaced = "net.minecraft.launchwrapper.Launch";
            var resultModel = new RawVersionModel
            {
                Id = id,
                Time = time,
                ReleaseTime = time,
                Libraries = libraries,
                MainClreplaced = mainClreplaced,
                InheritsFrom = VersionModel.McVersion,
                BuildType = VersionModel.Type,
                JarFile = InheritVersion.JarFile ?? InheritVersion.Id
            };

            if (InheritVersion.Arguments != null)
                resultModel.Arguments = new Arguments
                {
                    Game = new List<object>
                    {
                        "--tweakClreplaced",
                        VersionModel.Build.TweakClreplaced
                    }
                };
            else
                resultModel.MinecraftArguments =
                    $"{InheritVersion.MinecraftArguments} --tweakClreplaced {VersionModel.Build.TweakClreplaced}";

            var gamePath = Path.Combine(RootPath, GamePathHelper.GetGamePath(id));
            var di = new DirectoryInfo(gamePath);

            if (!di.Exists)
                di.Create();
            else
                DirectoryHelper.CleanDirectory(di.FullName);

            var jsonPath = GamePathHelper.GetGameJsonPath(RootPath, id);
            var jsonContent = JsonConvert.SerializeObject(resultModel, JsonHelper.CamelCasePropertyNamesSettings);

            await File.WriteAllTextAsync(jsonPath, jsonContent);

            InvokeStatusChangedEvent("LiteLoader 安装完成", 100);

            return id;
        }

19 Source : OptifineInstaller.cs
with MIT License
from Corona-Studio

public async Task<string> InstallTaskAsync()
        {
            InvokeStatusChangedEvent("开始安装 Optifine", 0);
            var mcVersion = OptifineDownloadVersion.McVersion;
            var edition = OptifineDownloadVersion.Type;
            var release = OptifineDownloadVersion.Patch;
            var editionRelease = $"{edition}_{release}";
            var id = string.IsNullOrEmpty(CustomId)
                ? $"{mcVersion}-Optifine_{editionRelease}"
                : CustomId;

            var versionPath = Path.Combine(RootPath, GamePathHelper.GetGamePath(id));
            var di = new DirectoryInfo(versionPath);

            if (!di.Exists)
                di.Create();

            InvokeStatusChangedEvent("读取 Optifine 数据", 20);
            using var archive = ArchiveFactory.Open(OptifineJarPath);
            var entries = archive.Entries;

            var launchWrapperVersion = "1.7";

            foreach (var entry in entries)
            {
                if (!entry.Key.Equals("launchwrapper-of.txt", StringComparison.OrdinalIgnoreCase)) continue;
                await using var stream = entry.OpenEntryStream();
                using var sr = new StreamReader(stream, Encoding.UTF8);
                launchWrapperVersion = await sr.ReadToEndAsync();
            }

            var launchWrapperEntry =
                entries.First(x => x.Key.Equals($"launchwrapper-of-{launchWrapperVersion}.jar"));

            InvokeStatusChangedEvent("生成版本总成", 40);

            var versionModel = new RawVersionModel
            {
                Id = id,
                InheritsFrom = mcVersion,
                Arguments = new Arguments
                {
                    Game = new List<object>
                    {
                        "--tweakClreplaced",
                        "optifine.OptiFineTweaker"
                    },
                    Jvm = new List<object>()
                },
                ReleaseTime = DateTime.Now,
                Time = DateTime.Now,
                BuildType = "release",
                Libraries = new List<Library>
                {
                    new()
                    {
                        Name = $"optifine:launchwrapper-of:{launchWrapperVersion}"
                    },
                    new()
                    {
                        Name = $"optifine:Optifine:{OptifineDownloadVersion.McVersion}_{editionRelease}"
                    }
                },
                MainClreplaced = "net.minecraft.launchwrapper.Launch",
                MinimumLauncherVersion = 21
            };

            var versionJsonPath = GamePathHelper.GetGameJsonPath(RootPath, id);
            var jsonStr = JsonConvert.SerializeObject(versionModel, JsonHelper.CamelCasePropertyNamesSettings);
            await File.WriteAllTextAsync(versionJsonPath, jsonStr);

            var librariesPath = Path.Combine(RootPath, GamePathHelper.GetLibraryRootPath(), "optifine",
                "launchwrapper-of",
                launchWrapperVersion);
            var libDi = new DirectoryInfo(librariesPath);

            InvokeStatusChangedEvent("写入 Optifine 数据", 60);

            if (!libDi.Exists)
                libDi.Create();

            var launchWrapperPath = Path.Combine(librariesPath,
                $"launchwrapper-of-{launchWrapperVersion}.jar");
            if (!File.Exists(launchWrapperPath))
            {
                await using var launchWrapperFs = File.OpenWrite(launchWrapperPath);
                launchWrapperEntry.WriteTo(launchWrapperFs);
            }

            var gameJarPath = Path.Combine(RootPath,
                GamePathHelper.GetGameExecutablePath(OptifineDownloadVersion.McVersion));
            var optifineLibPath = Path.Combine(RootPath, GamePathHelper.GetLibraryRootPath(), "optifine", "Optifine",
                $"{OptifineDownloadVersion.McVersion}_{editionRelease}",
                $"Optifine-{OptifineDownloadVersion.McVersion}_{editionRelease}.jar");

            var optifineLibPathDi = new DirectoryInfo(Path.GetDirectoryName(optifineLibPath)!);
            if (!optifineLibPathDi.Exists)
                optifineLibPathDi.Create();

            InvokeStatusChangedEvent("执行安装脚本", 80);

            var ps = new ProcessStartInfo(JavaExecutablePath)
            {
                ArgumentList =
                {
                    "-cp",
                    OptifineJarPath,
                    "optifine.Patcher",
                    Path.GetFullPath(gameJarPath),
                    OptifineJarPath,
                    Path.GetFullPath(optifineLibPath)
                },
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false
            };

            var p = Process.Start(ps);
            if (p == null)
                throw new NullReferenceException();

            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            void LogReceivedEvent(object sender, DataReceivedEventArgs args)
            {
                InvokeStatusChangedEvent(args.Data ?? "loading...", 85);
            }

            p.OutputDataReceived += LogReceivedEvent;

            var errList = new List<string>();
            p.ErrorDataReceived += (sender, args) =>
            {
                LogReceivedEvent(sender, args);

                if (!string.IsNullOrEmpty(args.Data))
                    errList.Add(args.Data);
            };

            await p.WaitForExitAsync();
            InvokeStatusChangedEvent("安装即将完成", 90);

            if (errList.Any())
                throw new NullReferenceException();

            InvokeStatusChangedEvent("Optifine 安装完成", 100);

            return id;
        }

19 Source : AssetInfoResolver.cs
with MIT License
from Corona-Studio

public async Task<IEnumerable<IGameResource>> ResolveResourceAsync()
        {
            LogGameResourceInfoResolveStatus("开始进行游戏资源(replacedet)检查");

            if (!(Versions?.Any() ?? false) && VersionInfo?.replacedetInfo == null) return Enumerable.Empty<IGameResource>();

            var isreplacedetInfoNotExists = 
                string.IsNullOrEmpty(VersionInfo?.replacedetInfo?.Url) &&
                string.IsNullOrEmpty(VersionInfo?.replacedetInfo?.Id);
            if (isreplacedetInfoNotExists &&
                string.IsNullOrEmpty(VersionInfo?.replacedets))
                return Enumerable.Empty<IGameResource>();

            var replacedetIndexesDi =
                new DirectoryInfo(Path.Combine(BasePath, GamePathHelper.GetreplacedetsRoot(), "indexes"));
            var replacedetObjectsDi =
                new DirectoryInfo(Path.Combine(BasePath, GamePathHelper.GetreplacedetsRoot(), "objects"));

            if (!replacedetIndexesDi.Exists) replacedetIndexesDi.Create();
            if (!replacedetObjectsDi.Exists) replacedetObjectsDi.Create();

            var id = VersionInfo?.replacedetInfo?.Id ?? VersionInfo.replacedets;
            var replacedetIndexesPath = Path.Combine(replacedetIndexesDi.FullName, $"{id}.json");
            if (!File.Exists(replacedetIndexesPath))
            {
                LogGameResourceInfoResolveStatus("没有发现replacedet Indexes 文件, 开始下载");

                var replacedetIndexDownloadUri = VersionInfo?.replacedetInfo?.Url;

                if (isreplacedetInfoNotExists)
                {
                    var versionObject = Versions?.FirstOrDefault(v => v.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
                    if (versionObject == default) return Enumerable.Empty<IGameResource>();

                    var jsonRes = await HttpHelper.Get(versionObject.Url);
                    var jsonStr = await jsonRes.Content.ReadreplacedtringAsync();
                    var versionModel = JsonConvert.DeserializeObject<RawVersionModel>(jsonStr);

                    if (versionModel == default) return Enumerable.Empty<IGameResource>();

                    replacedetIndexDownloadUri = versionModel.replacedetIndex?.Url;
                }

                if (string.IsNullOrEmpty(replacedetIndexDownloadUri)) return Enumerable.Empty<IGameResource>();

                if (!string.IsNullOrEmpty(replacedetIndexUriRoot))
                {
                    var replacedetIndexUriRoot = HttpHelper.RegexMatchUri(replacedetIndexDownloadUri);
                    replacedetIndexDownloadUri =
                        $"{replacedetIndexUriRoot}{replacedetIndexDownloadUri[replacedetIndexUriRoot.Length..]}";
                }

                var dp = new DownloadFile
                {
                    DownloadPath = replacedetIndexesDi.FullName,
                    FileName = $"{id}.json",
                    DownloadUri = replacedetIndexDownloadUri
                };

                try
                {
                    await DownloadHelper.DownloadData(dp);
                }
                catch (Exception e)
                {
                    LogGameResourceInfoResolveStatus($"解析replacedet Indexes 文件失败!原因:{e.Message}", logType: LogType.Error);
                    return Enumerable.Empty<IGameResource>();
                }

                LogGameResourceInfoResolveStatus("replacedet Indexes 文件下载完成", 100, LogType.Success);
            }

            LogGameResourceInfoResolveStatus("开始解析replacedet Indexes 文件...");

            replacedetObjectModel replacedetObject;
            try
            {
                var content = await File.ReadAllTextAsync(replacedetIndexesPath);
                replacedetObject = JsonConvert.DeserializeObject<replacedetObjectModel>(content);
            }
            catch (Exception ex)
            {
                LogGameResourceInfoResolveStatus($"解析replacedet Indexes 文件失败!原因:{ex.Message}", logType: LogType.Error);
                File.Delete(replacedetIndexesPath);
                return Enumerable.Empty<IGameResource>();
            }

            if (replacedetObject == null)
            {
                LogGameResourceInfoResolveStatus("解析replacedet Indexes 文件失败!原因:文件可能损坏或为空", logType: LogType.Error);
                File.Delete(replacedetIndexesPath);
                return Enumerable.Empty<IGameResource>();
            }

#pragma warning disable CA5350 // 不要使用弱加密算法
            using var hA = SHA1.Create();
#pragma warning restore CA5350 // 不要使用弱加密算法

            var checkedObject = 0;
            var objectCount = replacedetObject.Objects.Count;
            var result = new ConcurrentBag<IGameResource>();

            LogGameResourceInfoResolveStatus("检索并验证 replacedet 资源", 0);
            Parallel.ForEach(replacedetObject.Objects,
                new ParallelOptions
                {
                    MaxDegreeOfParallelism = 2
                }, async obj =>
                {
                    var (_, fi) = obj;
                    var hash = fi.Hash;
                    var twoDigitsHash = hash[..2];
                    var path = Path.Combine(replacedetObjectsDi.FullName, twoDigitsHash);
                    var filePath = Path.Combine(path, fi.Hash);

                    Interlocked.Increment(ref checkedObject);
                    var progress = (double) checkedObject / objectCount * 100;
                    LogGameResourceInfoResolveStatus(string.Empty, progress);

                    if (File.Exists(filePath))
                    {
                        if (!CheckLocalFiles) return;
                        try
                        {
                            var computedHash = await CryptoHelper.ComputeFileHashAsync(filePath, hA);
                            if (computedHash.Equals(fi.Hash, StringComparison.OrdinalIgnoreCase)) return;

                            File.Delete(filePath);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    result.Add(new replacedetDownloadInfo
                    {
                        replacedle = hash,
                        Path = path,
                        Type = "replacedet",
                        Uri = $"{replacedetUriRoot}{twoDigitsHash}/{fi.Hash}",
                        FileSize = fi.Size,
                        CheckSum = hash,
                        FileName = hash
                    });
                });

            LogGameResourceInfoResolveStatus("replacedets 解析完成", 100, logType: LogType.Success);

            return result;
        }

19 Source : LibraryInfoResolver.cs
with MIT License
from Corona-Studio

public async Task<IEnumerable<IGameResource>> ResolveResourceAsync()
        {
            LogGameResourceInfoResolveStatus("开始进行游戏资源(Library)检查");
            if (!(VersionInfo?.Natives?.Any() ?? false) &&
                !(VersionInfo?.Libraries?.Any() ?? false))
                return Enumerable.Empty<IGameResource>();

            var libDi = new DirectoryInfo(Path.Combine(BasePath, GamePathHelper.GetLibraryRootPath()));

            if (!libDi.Exists) libDi.Create();

#pragma warning disable CA5350 // 不要使用弱加密算法
            using var hA = SHA1.Create();
#pragma warning restore CA5350 // 不要使用弱加密算法

            var checkedLib = 0;
            var libCount = VersionInfo.Libraries.Count;
            var checkedResult = new ConcurrentBag<FileInfo>();

            Parallel.ForEach(VersionInfo.Libraries,
                new ParallelOptions
                {
                    MaxDegreeOfParallelism = 2
                },
                async lib =>
                {
                    var libPath = GamePathHelper.GetLibraryPath(lib.Path.Replace('/', '\\'));
                    var filePath = Path.Combine(BasePath, libPath);

                    Interlocked.Increment(ref checkedLib);
                    var progress = (double)checkedLib / libCount * 100;

                    LogGameResourceInfoResolveStatus("检索并验证 Library", progress);

                    if (File.Exists(filePath))
                    {
                        if (!CheckLocalFiles) return;
                        if (string.IsNullOrEmpty(lib.Sha1)) return;

                        try
                        {
                            var computedHash = await CryptoHelper.ComputeFileHashAsync(filePath, hA);
                            if (computedHash.Equals(lib.Sha1, StringComparison.OrdinalIgnoreCase)) return;

                            File.Delete(filePath);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    checkedResult.Add(lib);
                });

            checkedLib = 0;
            libCount = VersionInfo.Natives.Count;

            Parallel.ForEach(VersionInfo.Natives,
                new ParallelOptions
                {
                    MaxDegreeOfParallelism = 2
                },
                async native =>
                {
                    var nativePath = GamePathHelper.GetLibraryPath(native.FileInfo.Path.Replace('/', '\\'));
                    var filePath = Path.Combine(BasePath, nativePath);

                    if (File.Exists(filePath))
                    {
                        if (!CheckLocalFiles) return;
                        if (string.IsNullOrEmpty(native.FileInfo.Sha1)) return;

                        Interlocked.Increment(ref checkedLib);
                        var progress = (double)checkedLib / libCount * 100;
                        LogGameResourceInfoResolveStatus("检索并验证 Native", progress);

                        try
                        {
                            var computedHash = await CryptoHelper.ComputeFileHashAsync(filePath, hA);
                            if (computedHash.Equals(native.FileInfo.Sha1, StringComparison.OrdinalIgnoreCase)) return;

                            File.Delete(filePath);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    checkedResult.Add(native.FileInfo);
                });

            var result = new List<IGameResource>();
            foreach (var lL in checkedResult)
            {
                string uri;
                if (lL.Name.StartsWith("forge", StringComparison.Ordinal) ||
                    lL.Name.StartsWith("net.minecraftforge", StringComparison.Ordinal))
                    uri = $"{ForgeUriRoot}{lL.Path.Replace('\\', '/')}";
                else
                    uri = $"{LibraryUriRoot}{lL.Path.Replace('\\', '/')}";

                var symbolIndex = lL.Path.LastIndexOf('/');
                var fileName = lL.Path[(symbolIndex + 1)..];
                var path = Path.Combine(BasePath,
                    GamePathHelper.GetLibraryPath(lL.Path[..symbolIndex].Replace('/', '\\')));

                result.Add(
                    new LibraryDownloadInfo
                    {
                        Path = path,
                        replacedle = lL.Name.Split(':')[1],
                        Type = "Library/Native",
                        Uri = uri,
                        FileSize = lL.Size,
                        CheckSum = lL.Sha1,
                        FileName = fileName
                    });
            }

            await Task.Delay(1);

            LogGameResourceInfoResolveStatus("检查Library完成", 100);

            return result;
        }

19 Source : SavingStrategy.cs
with Apache License 2.0
from cosmos-loops

public string CheckAndGetFilePath(ILogEventInfo logEventInfo) {
            var targetPath = GetFilePath(logEventInfo);

            if (!System.IO.File.Exists(targetPath)) {
                var fi = new FileInfo(targetPath);
                var di = fi.Directory;

                if (di == null) {
                    return string.Empty;
                }

                if (!di.Exists) {
                    di.Create();
                }
            }

            return targetPath;
        }

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

public static void GenerateHtmlReport(CoverageResult coverageResult, IReporter reporter = null, string sourceFileFilter = "", [CallerMemberName] string directory = "")
        {
            JsonReporter defaultReporter = new JsonReporter();
            reporter ??= new CoberturaReporter();
            DirectoryInfo dir = Directory.CreateDirectory(directory);
            dir.Delete(true);
            dir.Create();
            string reportFile = Path.Combine(dir.FullName, Path.ChangeExtension("report", defaultReporter.Extension));
            File.WriteAllText(reportFile, defaultReporter.Report(coverageResult, new Mock<ISourceRootTranslator>().Object));
            reportFile = Path.Combine(dir.FullName, Path.ChangeExtension("report", reporter.Extension));
            File.WriteAllText(reportFile, reporter.Report(coverageResult, new Mock<ISourceRootTranslator>().Object));
            // i.e. reportgenerator -reports:"C:\git\coverlet\test\coverlet.core.tests\bin\Debug\netcoreapp2.0\Condition_If\report.cobertura.xml" -targetdir:"C:\git\coverlet\test\coverlet.core.tests\bin\Debug\netcoreapp2.0\Condition_If" -filefilters:+**\Samples\Instrumentation.cs
            replacedert.True(new Generator().GenerateReport(new ReportConfiguration(
            new[] { reportFile },
            dir.FullName,
            new string[0],
            null,
            new string[0],
            new string[0],
            new string[0],
            new string[0],
            string.IsNullOrEmpty(sourceFileFilter) ? new string[0] : new[] { sourceFileFilter },
            null,
            null)));
        }

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

private static void WriteHits(object sender)
        {
            if (_enableLog)
            {
                replacedembly currentreplacedembly = replacedembly.GetExecutingreplacedembly();
                DirectoryInfo location = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(currentreplacedembly.Location), "TrackerreplacedLog"));
                location.Create();
                string logFile = Path.Combine(location.FullName, $"{Path.GetFileName(currentreplacedembly.Location)}_{DateTime.UtcNow.Ticks}_{Process.GetCurrentProcess().Id}.txt");
                using (var fs = new FileStream(HitsFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                using (var log = new FileStream(logFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
                using (var logWriter = new StreamWriter(log))
                using (var br = new BinaryReader(fs))
                {
                    int hitsLength = br.ReadInt32();
                    for (int i = 0; i < hitsLength; ++i)
                    {
                        logWriter.WriteLine($"{i},{br.ReadInt32()}");
                    }
                }

                File.AppendAllText(logFile, $"Hits flushed file path {HitsFilePath} location '{replacedembly.GetExecutingreplacedembly().Location}' by '{sender ?? "null"}'");
            }
        }

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

[Fact]
        public void TestIncludeDirectories()
        {
            string module = typeof(InstrumentationHelperTests).replacedembly.Location;
            DirectoryInfo newDir = Directory.CreateDirectory("TestIncludeDirectories");
            newDir.Delete(true);
            newDir.Create();
            DirectoryInfo newDir2 = Directory.CreateDirectory("TestIncludeDirectories2");
            newDir2.Delete(true);
            newDir2.Create();

            File.Copy(module, Path.Combine(newDir.FullName, Path.GetFileName(module)));
            module = Path.Combine(newDir.FullName, Path.GetFileName(module));
            File.Copy("coverlet.msbuild.tasks.dll", Path.Combine(newDir.FullName, "coverlet.msbuild.tasks.dll"));
            File.Copy("coverlet.core.dll", Path.Combine(newDir2.FullName, "coverlet.core.dll"));

            var currentDirModules = _instrumentationHelper.GetCoverableModules(module, Array.Empty<string>(), false);
            replacedert.Single(currentDirModules);
            replacedert.Equal("coverlet.msbuild.tasks.dll", Path.GetFileName(currentDirModules[0]));

            var moreThanOneDirectory = _instrumentationHelper
                                       .GetCoverableModules(module, new string[] { newDir2.FullName }, false)
                                       .OrderBy(f => f).ToArray();

            replacedert.Equal(2, moreThanOneDirectory.Length);
            replacedert.Equal("coverlet.msbuild.tasks.dll", Path.GetFileName(moreThanOneDirectory[0]));
            replacedert.Equal("coverlet.core.dll", Path.GetFileName(moreThanOneDirectory[1]));

            var moreThanOneDirectoryPlusTestreplacedembly = _instrumentationHelper
                                                       .GetCoverableModules(module, new string[] { newDir2.FullName }, true)
                                                       .OrderBy(f => f).ToArray();

            replacedert.Equal(3, moreThanOneDirectoryPlusTestreplacedembly.Length);
            replacedert.Equal("coverlet.core.tests.dll", Path.GetFileName(moreThanOneDirectoryPlusTestreplacedembly[0]));
            replacedert.Equal("coverlet.msbuild.tasks.dll", Path.GetFileName(moreThanOneDirectoryPlusTestreplacedembly[1]));
            replacedert.Equal("coverlet.core.dll", Path.GetFileName(moreThanOneDirectoryPlusTestreplacedembly[2]));

            newDir.Delete(true);
            newDir2.Delete(true);
        }

19 Source : System_IO_DirectoryInfo_Binding.cs
with MIT License
from CragonGame

static StackObject* Create_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject* ptr_of_this_method;
            StackObject* __ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.DirectoryInfo instance_of_this_method = (System.IO.DirectoryInfo)typeof(System.IO.DirectoryInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.Create();

            return __ret;
        }

19 Source : FileExtensions.cs
with Apache License 2.0
from cs-util-com

public static DirectoryInfo CreateV2(this DirectoryInfo self) {
            if (!self.ExistsV2()) { self.Create(); self.Refresh(); }
            return self;
        }

19 Source : ActionBuild.cs
with MIT License
from csharpfritz

internal void BuildPosts()
		{

			var postsFolder = new DirectoryInfo(Path.Combine(WorkingDirectory, "posts"));
			var outputFolder = new DirectoryInfo(Path.Combine(WorkingDirectory, OutputPath, "posts"));
			if (!outputFolder.Exists) outputFolder.Create();

			var pipeline = new MarkdownPipelineBuilder()
					.UseAdvancedExtensions()
					.UseYamlFrontMatter()
					.UsePrism()
					.Build();

			// Load layout for post
			var layoutText = File.ReadAllText(Path.Combine(WorkingDirectory, "themes", Config.Theme, "layouts", "posts.html"));

			foreach (var post in postsFolder.GetFiles("*.md"))
			{

				var txt = File.ReadAllText(post.FullName, Encoding.UTF8);

				var baseName = Path.Combine(post.Name[0..^3] + ".html");
				var fileName = Path.Combine(outputFolder.FullName, baseName);

				var doc = Markdig.Markdown.Parse(txt, pipeline);
				var fm = txt.GetFrontMatter<Frontmatter>();
				var mdHTML = Markdig.Markdown.ToHtml(doc, pipeline);

				if (Force || post.LastWriteTimeUtc > (_LastBuild?.Timestamp ?? DateTime.MinValue)) {

					string outputHTML = layoutText.Replace("{{ Body }}", mdHTML);
					outputHTML = fm.Format(outputHTML);
					outputHTML = Minify(outputHTML);

					File.WriteAllText(fileName, outputHTML);

				}

				_Posts.Add(new PostData
				{
					Abstract = mdHTML,
					Filename = $"posts/{baseName}",
					Frontmatter = fm,
					LastUpdate = post.LastWriteTimeUtc
				});

			}


		}

19 Source : TestSiteBaseFixture.cs
with MIT License
from csharpfritz

private void InitializeOutputFolder(string workingDirectory)
		{
			OutputFolder = new DirectoryInfo(workingDirectory);
			if (!OutputFolder.Exists)
			{
				folderLock.EnterWriteLock();
				OutputFolder.Create();
				folderLock.ExitWriteLock();
			}
			OutputPostsFolder = new DirectoryInfo(Path.Combine(OutputFolder.FullName, "posts"));
		}

19 Source : BaseTemplatedManifestGenerator.cs
with MIT License
from dansiegel

protected override void ExecuteInternal()
        {
            Outputs = ManifestOutputPath;

            if (!File.Exists(ManifestInputPath))
            {
                Log?.LogWarning("There is no Template Manifest at the path: '{0}'", ManifestInputPath);
                return;
            }

            var outputInfo = new FileInfo(ManifestOutputPath);
            if (!outputInfo.Directory.Exists)
                outputInfo.Directory.Create();

            var template = ReadManifest();

            var variables = Utils.Environmentreplacedyzer.GatherEnvironmentVariables(Build, true);
            foreach (Match match in GetMatches(template))
            {
                template = ProcessMatch(template, match, variables);
            }

            if (variables.ContainsKey(Constants.AppPackageName))
            {
                Log.LogMessage($"Setting App Package Name to: {variables[Constants.AppPackageName]}");
                template = SetAppBundleId(template, variables[Constants.AppPackageName]);
            }

            SaveManifest(template);
        }

19 Source : ReleaseNotesGenerator.cs
with MIT License
from dansiegel

protected override void ExecuteInternal()
        {
            var releaseNotesOptions = Build.Configuration.ReleaseNotes;

            if (releaseNotesOptions.Disable ?? false) return;

            var rootDirectory = ConfigHelper.GetConfigurationPath(Build.ProjectDirectory, Build.SolutionDirectory);
            var releaseNotesFilePath = new FileInfo(Path.Combine(releaseNotesOptions.CreateInRoot ? rootDirectory : OutputPath, releaseNotesOptions.FileName ?? "ReleaseNotes.txt"));

            if (!releaseNotesFilePath.Directory.Exists)
                releaseNotesFilePath.Directory.Create();

            var branchName = GetBranchName();
            if (string.IsNullOrWhiteSpace(branchName))
            {
                Log.LogMessage("It appears the git repo is in a disconnected state, unable to determine the current branch name");
                return;
            }

            var fromDate = DateTime.Now.AddDays(releaseNotesOptions.MaxDays > 0 ? releaseNotesOptions.MaxDays * -1 : releaseNotesOptions.MaxDays);

            //"git log --no-merges --since="$TODAY 00:00:00" --format=" % cd" --date=short";
            var dates = GetCommitDates(fromDate);
            var notes = string.Empty;
            var characterLimitExceeded = false;
            var commits = 0;

            foreach (var date in dates)
            {
                // 2018-07-25
                //"git log --no-merges --format=" * % s" --since="2018-07-25 00:00:00" --until="2018-07-25 24:00:00""
                if (commits > Build.Configuration.ReleaseNotes.MaxCommit || characterLimitExceeded)
                {
                    Log.LogMessage("Maximimum limits reaches. Truncating Release Notes.");
                    break;
                }

                var lines = GetCommitMessages(date);
                foreach (var line in lines)
                {
                    if (string.IsNullOrEmpty(line))
                        continue;

                    if (releaseNotesOptions.MaxCommit > 0 && commits++ > releaseNotesOptions.MaxCommit)
                        break;
                    if(releaseNotesOptions.CharacterLimit > 0 && line.Length + notes.Length > releaseNotesOptions.CharacterLimit)
                    {
                        characterLimitExceeded = true;
                        break;
                    }
                    notes += $"{line}\n";
                }
            }

            File.WriteAllText(releaseNotesFilePath.FullName, notes.Trim());

        }

19 Source : ConfigurationManagerHandlerTask.cs
with MIT License
from dansiegel

internal override void ExecuteInternal(IBuildConfiguration config)
        {
            // Validate we have inputs...
            if (InputConfigFiles is null || !InputConfigFiles.Any())
            {
                Log.LogMessage("No input config files were found");
                return;
            }

            if(GeneratedAppConfig is null || !GeneratedAppConfig.Any())
            {
                Log.LogError("Input app.config's were found, however no outputs were found.");
                return;
            }

            // Get root app.config
            var rootConfigFile = GetTaskItem(InputConfigFiles, "app.config");
            if (rootConfigFile is null)
            {
                // this should never happen...
                Log.LogError("We could not locate an 'app.config'. Please file a bug.");
                return;
            }

            // Reset output directory
            var fi = new FileInfo(GeneratedAppConfig.First().ItemSpec);
            if(fi.Directory.Exists)
            {
                fi.Directory.Delete(true);
            }
            fi.Directory.Create();

            // Get Transform config
            var transformFile = GetTaskItem(InputConfigFiles, $"app.{AppConfigEnvironment}.config");
            var outputs = GeneratedAppConfig.Select(x => x.ToExpectedAppConfig());
            var generator = new ConfigurationManagerTransformationGenerator(config)
            {
                BaseConfigPath = rootConfigFile.ItemSpec,
                TransformFilePath = transformFile.ItemSpec,
                ExpectedConfigs = outputs
            };
            generator.Execute();
        }

19 Source : GoogleTask.cs
with MIT License
from dansiegel

internal static string GetResourcePath(string environmentVariable, string intermediateOutputPath, string logicalName)
        {
            if (string.IsNullOrEmpty(environmentVariable))
                return null;

            var variables = Environment.GetEnvironmentVariables().Keys.Cast<string>();
            var variableName = variables.FirstOrDefault(x => x.Equals(environmentVariable, StringComparison.InvariantCultureIgnoreCase));

            if (string.IsNullOrEmpty(variableName))
                return null;

            var value = Environment.GetEnvironmentVariable(variableName);
            try
            {
                if (File.Exists(value))
                    return new FileInfo(value).FullName;
            }
            catch
            {
                // Suppress errors
            }

            var directory = new DirectoryInfo(Path.Combine(intermediateOutputPath, "google-services"));
            directory.Create();
            var path = Path.Combine(directory.FullName, logicalName);
            File.WriteAllText(path, value);
            return path;
        }

19 Source : SocketMessengerCacheTests.cs
with MIT License
from dansiegel

private static void DeleteCache()
        {
            var fi = new FileInfo(SocketMessenger.LogCacheFile);
            if (fi.Exists)
                fi.Delete();

            if (!fi.Directory.Exists)
                fi.Directory.Create();
        }

19 Source : ImageCollectionGeneratorFixture.cs
with MIT License
from dansiegel

private void Initialize()
        {
            var rdInfo = new FileInfo(Path.Combine("resources", "resourceDefinition.json"));
            if (!rdInfo.Exists)
            {
                rdInfo.Directory.Create();
                _testOutputHelper.WriteLine("Adding resourceDefinition file");
                var replacedembly = GetType().replacedembly;
                using var stream = replacedembly.GetManifestResourceStream("Mobile.BuildTools.Tests.resources.resourceDefinition.json");
                using var fs = rdInfo.Create();
                stream.CopyTo(fs);
            }
        }

19 Source : SocketMessenger.cs
with MIT License
from dansiegel

internal static void SaveCache(Queue<LogMessage> queue)
        {
            lock (lockObject)
            {
                var cacheFile = new FileInfo(LogCacheFile);

                if (!cacheFile.Directory.Exists)
                    cacheFile.Directory.Create();

                var json = JsonSerializer.Serialize(queue, Options);
                File.WriteAllText(cacheFile.FullName, json);
            }
        }

19 Source : Updater.cs
with GNU General Public License v3.0
from DarwinBaker

private void MirrorSourceToDestination()
        {
            try
            {
                StatusChanged(STATUS_2, "Deleting depricated files...");
                int processed = 0;

                try
                {
                    File.Delete("AATool.exe");
                }
                catch { }

                try
                {
                    File.Delete("AAUpdate.exe");
                }
                catch { }

                try
                {
                    File.Delete("VersionHistory.txt");
                }
                catch { }

                foreach (string file in this.oldFiles)
                {
                    processed++;
                    ProgressChanged(PROGRESS_2, (processed, oldFiles.Count));

                    //if file from current install isn't in latest release delete it
                    if (!this.newFiles.Contains(Path.Combine("replacedets", file)))
                    {
                        StatusChanged(STATUS_3, file);
                        File.Delete(Path.Combine(this.Destination.FullName, "replacedets", file));
                    }
                }
                //clear out any empty directories
                this.DeleteEmptyDirectories(this.Destination);

                StatusChanged(STATUS_2, "Copying updated files...");
                processed = 0;
                foreach (string file in this.newFiles)
                {
                    processed++;
                    ProgressChanged(PROGRESS_2, (processed, this.newFiles.Count));
                    StatusChanged(STATUS_3, file);

                    //if file from latest release isn't in current install or is different replace it
                    var oldInfo = new FileInfo(Path.Combine(this.Destination.FullName, file));
                    var newInfo = new FileInfo(Path.Combine(this.Source.FullName, file));
                    if (!oldInfo.Exists || !FileContentsEqual(oldInfo, newInfo))
                    {
                        oldInfo.Directory.Create();
                        newInfo.CopyTo(oldInfo.FullName, true);
                    }
                }
            }
            catch (Exception) { }
        }

19 Source : ReadWrite.cs
with MIT License
from DataMesh-OpenSource

public void CreateDir(string DirPath)
        {
            if (Directory.Exists(DirPath))
            {
            }
            else
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(DirPath);
                directoryInfo.Create();
            }
        }

19 Source : thcrap.cs
with BSD 2-Clause "Simplified" License
from David-JonesDVN

private void addRepo(string repojs, bool offline = false)
        {
            try
            {
                repoData data = JsonConvert.DeserializeObject<repoData>(repojs);
                FileInfo jsPath = new FileInfo(MainForm.curCfg.crapDir + "\\repos\\" + data.id + "\\repo.js");
                jsPath.Directory.Create();
                File.WriteAllText(jsPath.FullName, repojs);
                if (!repoList.Items.ContainsKey(data.id) || (bool)repoList.Items[data.id].Tag == true)
                {
                    foreach (string neighbor in data.neighbors)
                    {
                        searchRepo(neighbor, true);
                    }
                    repos[data.id] = data;
                    if (!repoList.Items.ContainsKey(data.id))
                    {
                        ListViewItem replacedle = repoList.Items.Add(data.replacedle);
                        replacedle.Name = data.id;
                        replacedle.Tag = offline;
                        replacedle.SubItems.Add(data.id);
                    }
                    else
                    {
                        ListViewItem replacedle = repoList.Items[data.id];
                        replacedle.Tag = offline;
                    }
                    repoList_SelectedIndexChanged(repoList.Items[data.id], new EventArgs());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

19 Source : thcrap.cs
with BSD 2-Clause "Simplified" License
from David-JonesDVN

private void onPatchGet(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                patchData patch = JsonConvert.DeserializeObject<patchData>(e.Result);
                FileInfo jsPath = new FileInfo(MainForm.curCfg.crapDir + "\\repos\\" + (string)e.UserState + "\\" + patch.id + "\\patch.js");
                jsPath.Directory.Create();
                File.WriteAllText(jsPath.FullName, e.Result);
                foreach (string dependency in patch.dependencies)
                {
                    string[] dependencySet = dependency.Split('/');
                    string repository = "";
                    if (dependencySet.Length == 1)
                    {
                        foreach (KeyValuePair<string, repoData> repo in repos)
                        {
                            if (repo.Value.patches.ContainsKey(dependencySet[0]))
                            {
                                repository = repo.Key;
                            }
                        }
                    }
                    else
                        repository = dependencySet[0];
                    addPatch(repository, dependencySet[dependencySet.Length - 1], patchStates.IndexOf((string)e.UserState + "/" + patch.id + "/"));
                }
            }
        }

19 Source : DumpModel.cs
with MIT License
from DavidSM64

private static void WriteAllTextures(List<Bitmap> textures, string modelName)
        {
            for(int img_index = 0; img_index < textures.Count; img_index++)
            {
                string filepath = Directory.GetCurrentDirectory() + "\\" + modelName + "\\" + img_index + ".png";
                (new FileInfo(filepath)).Directory.Create();
                textures[img_index].Save(filepath, System.Drawing.Imaging.ImageFormat.Png);
            }
        }

19 Source : Model3D.cs
with MIT License
from DavidSM64

public void dumpModelToOBJ(float scale)
        {
            StringBuilder objModel = new StringBuilder();
            StringBuilder objMtl = new StringBuilder();
            objModel.Append("mtllib Level.mtl" + Environment.NewLine);
           // string objModel = "mtllib Level.mtl" + Environment.NewLine;
           // string objMtl = "";
            int index_offset = 1;
            int img_index = 0;
            
            foreach(System.Drawing.Bitmap bmp in builder.TextureImages)
            {
                string filepath = Directory.GetCurrentDirectory() + "\\Level\\" + img_index + ".png";
                (new FileInfo(filepath)).Directory.Create();
                bmp.Save(filepath, System.Drawing.Imaging.ImageFormat.Png);
                objMtl.Append("newmtl Tex_" + img_index + Environment.NewLine);
                objMtl.Append("Ka 0.000000 0.000000 0.000000" + Environment.NewLine +
                    "Kd 1.000000 1.000000 1.000000" + Environment.NewLine +
                    "Ks 0.000000 0.000000 0.000000" + Environment.NewLine);
                objMtl.Append("map_Kd Level/" + img_index + ".png" + Environment.NewLine);
                img_index++;
            }

            for (int i = 0; i < meshes.Count; i++)
            {
                MeshData m = meshes[i];
                if (m.vertices.Length < 1)
                    continue;
                objModel.Append("usemtl Tex_" + i + Environment.NewLine);

                foreach (Vector3 vert in m.vertices)
                {
                    objModel.Append("v " + (vert.X * scale) + " " + (vert.Y * scale) + " " + (vert.Z * scale));
                    objModel.Append(Environment.NewLine);
                }

                foreach (Vector2 texCoord in m.texCoord)
                {
                    float X = texCoord.X, Y = texCoord.Y;
                    if (m.texture.TextureParamS == (int)All.ClampToEdge)
                        X = (X > 1.0f ? 1.0f : (X < 0.0f ? 0.0f : X));
                    if (m.texture.TextureParamT == (int)All.ClampToEdge)
                        Y = (Y > 1.0f ? 1.0f : (Y < 0.0f ? 0.0f : Y));
                    objModel.Append("vt " + X + " " + -Y + Environment.NewLine);
                }

                int largest_value = index_offset;
                for (int j = 0; j < m.indices.Length/3; j++)
                {
                    int v1 = (int)m.indices[(j * 3) + 0] + index_offset;
                    int v2 = (int)m.indices[(j * 3) + 1] + index_offset;
                    int v3 = (int)m.indices[(j * 3) + 2] + index_offset;
                    objModel.Append("f " + v1 + "/" + v1 + " " + v2 + "/" + v2 + " " + v3 + "/" + v3 + Environment.NewLine);

                    largest_value = Math.Max(v1, largest_value);
                    largest_value = Math.Max(v2, largest_value);
                    largest_value = Math.Max(v3, largest_value);
                }
                index_offset = largest_value + 1;
            }
            File.WriteAllText("Level.obj", objModel.ToString());
            File.WriteAllText("Level.mtl", objMtl.ToString());
        }

19 Source : CreateFolderAction.cs
with MIT License
from DCourtel

public override void Run(ref ReturnCodeAction returnCode)
        {
            Logger.Write("Running CreateFolder. FullPath = " + this.FullPath);

            try
            {
                this.FullPath = Tools.GetExpandedPath(this.FullPath);
                DirectoryInfo destinationFolder = new DirectoryInfo(this.FullPath);

                if (!destinationFolder.Exists)
                {
                    destinationFolder.Create();
                    destinationFolder.Refresh();
                    Logger.Write(destinationFolder.Exists ? "Successfully created : " + this.FullPath : "Unable to create : " + this.FullPath);
                }
                else
                { Logger.Write("The folder already exists."); }
            }
            catch (Exception ex)
            {
                Logger.Write("Failed to create the folder : " + this.FullPath + "\r\n" + ex.Message);
            }
            Logger.Write("End of CreateFolder.");
        }

19 Source : CreateTextFileAction.cs
with MIT License
from DCourtel

public override void Run(ref ReturnCodeAction returnCode)
        {
            Logger.Write("Running CreateTextFileAction. FilePath = " + this.FilePath + " and Filename = " + this.Filename);

            try
            {
                this.FilePath = Tools.GetExpandedPath(this.FilePath);
                DirectoryInfo folder = new DirectoryInfo(this.FilePath);

                if(!folder.Exists)
                {
                    Logger.Write("The folder doesn't exists. Creating the folder…");
                    folder.Create();
                    Logger.Write("Folder successfully created.");
                }
                StreamWriter writer = new StreamWriter(Path.Combine(this.FilePath, this.Filename), false, Encoding.Unicode);
                writer.Write(this.Content);
                writer.Close();

                Logger.Write("File successfully written");
            }
            catch (Exception ex)
            {
                Logger.Write("**** An error occurs : " + ex.Message);
            }

            Logger.Write("End of CreateTextFileAction.");
        }

19 Source : CopyFileAction.cs
with MIT License
from DCourtel

public override void Run(ref ReturnCodeAction returnCode)
        {
            Logger.Write("Running CopyFileAction. SourceFile = " + this.SourceFile + " and DestinationFolder = " + this.DestinationFolder);

            try
            {
                this.SourceFile = Tools.GetExpandedPath(this.SourceFile);
                this.DestinationFolder = Tools.GetExpandedPath(this.DestinationFolder);
                FileInfo sourceFile = new FileInfo(this.SourceFile);
                DirectoryInfo destinationFolder = new DirectoryInfo(this.DestinationFolder);

                if (!destinationFolder.Exists)
                {
                    Logger.Write("Creating : " + this.DestinationFolder);
                    destinationFolder.Create();
                }

                FileInfo destinationFile = sourceFile.CopyTo(Path.Combine(this.DestinationFolder, sourceFile.Name), true);
                if (destinationFile.Exists)
                { Logger.Write("Successfully copied : " + this.SourceFile + " to : " + this.DestinationFolder); }
                else
                { Logger.Write("Unable to copy : " + this.SourceFile + " to : " + this.DestinationFolder); }
            }
            catch (Exception ex)
            {
                Logger.Write("Failed to copy the file : " + this.SourceFile + " to : " + this.DestinationFolder + "\r\n" + ex.Message);
            }
            Logger.Write("End of CopyFileAction.");
        }

19 Source : RenameFileAction.cs
with MIT License
from DCourtel

[TestMethod]
            public void RenameTheFile_WhenCalled()
            {
                // Arrange
                SUT action = new SUT(Tools.GetXmlFragment("RenameFile.CustAct"));
                var finalResult = Tools.GetReturnCodeAction();
                FileInfo fileToRename = new FileInfo(action.FullPath);
                FileInfo fileRenamed = new FileInfo(Path.Combine(fileToRename.DirectoryName, action.NewName));
                if(!Directory.Exists(fileToRename.DirectoryName))
                {
                    fileToRename.Directory.Create();
                }
                if(!fileToRename.Exists)
                {
                    StreamWriter writer = fileToRename.CreateText();
                    writer.Write("This file must be rename.");
                    writer.Close();
                    fileToRename.Refresh();
                }
                if(fileRenamed.Exists)
                {
                    fileRenamed.Delete();
                }
                replacedert.IsTrue(fileToRename.Exists);
                replacedert.IsFalse(fileRenamed.Exists);

                // Act
                action.Run(ref finalResult);
                fileToRename.Refresh();
                fileRenamed.Refresh();

                // replacedert
                replacedert.IsFalse(fileToRename.Exists);
                replacedert.IsTrue(fileRenamed.Exists);
            }

19 Source : DeleteFolderAction.cs
with MIT License
from DCourtel

[TestMethod]
            public void DeleteTheFolder_WhenItExists()
            {
                // Arrange
                SUT action = new SUT(Tools.GetXmlFragment("DeleteFolderAction.CustAct"));
                DirectoryInfo folderToDelete = new DirectoryInfo(action.FolderPath);
                var finalResult = Tools.GetReturnCodeAction();

                // Act
                if (!folderToDelete.Exists)
                {
                    folderToDelete.Create();
                    folderToDelete.Refresh();
                    replacedert.IsTrue(folderToDelete.Exists);
                }
                action.Run(ref finalResult);
                folderToDelete.Refresh();

                // replacedert
                replacedert.IsFalse(folderToDelete.Exists);
            }

19 Source : DeleteFolderAction.cs
with MIT License
from DCourtel

[TestMethod]
            public void DeleteTheFolder_WhenItContainsFilesAndSubFolders()
            {
                // Arrange
                SUT action = new SUT(Tools.GetXmlFragment("DeleteFolderAction.CustAct"));
                DirectoryInfo folderToDelete = new DirectoryInfo(action.FolderPath);
                var finalResult = Tools.GetReturnCodeAction();

                // Act
                if (folderToDelete.Exists)
                {
                    folderToDelete.Delete(true);
                    folderToDelete.Refresh();
                    replacedert.IsFalse(folderToDelete.Exists);
                }
                folderToDelete.Create();
                folderToDelete.Refresh();
                replacedert.IsTrue(folderToDelete.Exists);
                folderToDelete.CreateSubdirectory(@"SecondLevel\ThirdLevel");
                folderToDelete.CreateSubdirectory("Another Folder");
                StreamWriter writer = new StreamWriter(Path.Combine(folderToDelete.FullName, "test1.txt"));
                writer.Write("test");
                writer.Close();

                writer = new StreamWriter(Path.Combine(folderToDelete.FullName, "test2.txt"));
                writer.Write("test");
                writer.Close();

                action.Run(ref finalResult);
                folderToDelete.Refresh();

                // replacedert
                replacedert.IsFalse(folderToDelete.Exists);
            }

19 Source : RenameFolderAction.cs
with MIT License
from DCourtel

[TestMethod]
            public void RenameTheFile_WhenCalled()
            {
                // Arrange
                SUT action = new SUT(Tools.GetXmlFragment("RenameFolder.CustAct"));
                var finalResult = Tools.GetReturnCodeAction();
                DirectoryInfo folderToRename = new DirectoryInfo(action.FolderPath);
                DirectoryInfo renamedFolder = new DirectoryInfo(Path.Combine(folderToRename.Parent.FullName, action.NewName));

                if (!folderToRename.Parent.Exists)
                {
                    folderToRename.Parent.Create();
                }
                if (!folderToRename.Exists)
                {
                    folderToRename.Create();
                }
                if(renamedFolder.Exists)
                {
                    renamedFolder.Delete();
                    renamedFolder.Refresh();
                }

                folderToRename.Refresh();
                replacedert.IsTrue(folderToRename.Exists);
                replacedert.IsFalse(renamedFolder.Exists);

                // Act
                action.Run(ref finalResult);
                folderToRename.Refresh();
                renamedFolder.Refresh();

                // replacedert
                replacedert.IsFalse(folderToRename.Exists);
                replacedert.IsTrue(renamedFolder.Exists);
            }

19 Source : DlgProfile.cs
with GNU General Public License v3.0
from Depressurizer

private bool CreateProfile()
        {
            if (!ValidateEntries())
            {
                return false;
            }

            FileInfo file;
            try
            {
                file = new FileInfo(txtFilePath.Text);
            }
            catch
            {
                MessageBox.Show(GlobalStrings.DlgProfile_YouMustEnterValidProfilePath, GlobalStrings.DBEditDlg_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (!file.Directory.Exists)
            {
                try
                {
                    file.Directory.Create();
                }
                catch
                {
                    MessageBox.Show(GlobalStrings.DlgProfile_FailedToCreateParentDirectory, GlobalStrings.DBEditDlg_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }

            Profile profile = new Profile();

            SaveModifiables(profile);
            AutoCat.GenerateDefaultAutoCatSet(profile.AutoCats);

            try
            {
                profile.Save(file.FullName);
            }
            catch (ApplicationException e)
            {
                MessageBox.Show(e.Message, GlobalStrings.DBEditDlg_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            Profile = profile;
            return true;
        }

19 Source : Program.cs
with MIT License
from diamondo25

static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Env arguments to use:");
                Console.WriteLine(" WZ_KEY - key for wz file, like '315' for maple version 315");
                Console.WriteLine(" WZ_MAP_NAME - name of the json file (without extension) that contains the tree of the wz contents.");
                Console.WriteLine(" MSEXE - path to MapleStory.exe. Will use MapleStory.exe from WZ directory if not set. Used for detecting version (and set WZ_MAP_NAME)");
                Console.WriteLine(" EXTRACT_IMGS=1 - also extract raw img files from wz");
                Console.WriteLine(" PRETTYPRINT_JSON=1 - pretty print json files (makes them huge)");
                Console.WriteLine(" EXPORT_BSON=1 - Use BSON instead of JSON for img files (images will be binary instead of base64)");
                Console.WriteLine(" OUTPUT_DIR - Write files to specified output dir, instead of the directory of the wz file");
                Console.WriteLine("Files to preplaced:");
                Console.WriteLine(" *.img files");
                Console.WriteLine(" *.wz files");
                Console.WriteLine();
            }
            else
            {

                exportBson = Environment.GetEnvironmentVariable("EXPORT_BSON") == "1";

                if (exportBson)
                {
                    Console.WriteLine("[OPT] Exporting as BSON");
                }

                var hadWzMapNameSet = Environment.GetEnvironmentVariable("WZ_MAP_NAME") != null;
                var useFileLocationAsOutputDir = Environment.GetEnvironmentVariable("OUTPUT_DIR") == null;
                if (!useFileLocationAsOutputDir)
                    globalOutputDirectory = new DirectoryInfo(Environment.GetEnvironmentVariable("OUTPUT_DIR"));

                if (globalOutputDirectory != null && !globalOutputDirectory.Exists) globalOutputDirectory.Create();

                foreach (var s in args)
                {
                    Console.WriteLine("Handling {0}", s);

                    var fileInfo = new FileInfo(s);


                    if (useFileLocationAsOutputDir)
                    {
                        globalOutputDirectory = fileInfo.Directory;
                    }


                    if (s.EndsWith(".img"))
                    {
                        var fsf = new FSFile
                        {
                            RealPath = fileInfo.FullName,
                            Name = fileInfo.Name,
                        };

                        ExtractFile(fsf, fileInfo.Directory);
                    }
                    else if (s.EndsWith(".wz"))
                    {
                        var msExe = Environment.GetEnvironmentVariable("MSEXE") ?? Path.Combine(fileInfo.DirectoryName, "MapleStory.exe");

                        if (File.Exists(msExe))
                        {
                            var fvi = FileVersionInfo.GetVersionInfo(msExe);
                            // Version is stored as locale.version.subversion.test
                            var version = fvi.FileMinorPart;
                            var subversion = fvi.FileBuildPart;
                            var locale = fvi.FileMajorPart;
                            Console.WriteLine(
                                "File for version {0}.{1} locale {2}",
                                version, subversion, locale
                            );

                            if (!hadWzMapNameSet)
                            {
                                var mapName = $"v{version}-{subversion}-{locale}";
                                Environment.SetEnvironmentVariable("WZ_MAP_NAME", mapName);
                            }
                        }
                        else if (!hadWzMapNameSet)
                        {
                            // Clear map name for files that did not match
                            Environment.SetEnvironmentVariable("WZ_MAP_NAME", null);
                        }


                        ExtractWZ(fileInfo, Environment.GetEnvironmentVariable("WZ_KEY") ?? "");
                    }
                    else
                    {
                        Console.WriteLine("Unable to handle file");
                    }
                }
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }

19 Source : Program.cs
with MIT License
from dolkensp

static void Main(string[] args)
		{
			var key = new Byte[] { 0x5E, 0x7A, 0x20, 0x02, 0x30, 0x2E, 0xEB, 0x1A, 0x3B, 0xB6, 0x17, 0xC3, 0x0F, 0xDE, 0x1E, 0x47 };

			if (args.Length == 0) args = new[] { @"Data.p4k" };

			if (args.Length == 1) args = new[] { args[0], "*.*" };

			using (var pakFile = File.OpenRead(args[0]))
			{
				var pak = new ZipFile(pakFile) { Key = key };
				byte[] buf = new byte[4096];

				foreach (ZipEntry entry in pak)
				{
					try
					{
						var crypto = entry.IsAesCrypted ? "Crypt" : "Plain";

						if (args[1].StartsWith("*.")) args[1] = args[1].Substring(1);                                                                                           // Enable *.ext format for extensions

						if (args[1] == ".*" ||                                                                                                                                 // Searching for everything
							args[1] == "*" ||                                                                                                                                   // Searching for everything
							entry.Name.ToLowerInvariant().Contains(args[1].ToLowerInvariant()) ||                                                                               // Searching for keywords / extensions
							(args[1].EndsWith("xml", StringComparison.InvariantCultureIgnoreCase) && entry.Name.EndsWith(".dcb", StringComparison.InvariantCultureIgnoreCase))) // Searching for XMLs - include game.dcb
						{
							var target = new FileInfo(entry.Name);

							if (!target.Directory.Exists) target.Directory.Create();

							if (!target.Exists)
							{
								Console.WriteLine($"{entry.CompressionMethod} | {crypto} | {entry.Name}");

								using (Stream s = pak.GetInputStream(entry))
								{
									using (FileStream fs = File.Create(entry.Name))
									{
										StreamUtils.Copy(s, fs, buf);
									}
								}

								// target.Delete();
							}
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine($"Exception while extracting {entry.Name}: {ex.Message}");

						try
						{
							using (var client = new HttpClient { })
							{
								// var server = "http://herald.holoxplor.local";
								var server = "https://herald.holoxplor.space";

								client.DefaultRequestHeaders.Add("client", "unp4k");

								using (var content = new MultipartFormDataContent("UPLOAD----"))
								{
									content.Add(new StringContent($"{ex.Message}\r\n\r\n{ex.StackTrace}"), "exception", entry.Name);

									using (var errorReport = client.PostAsync($"{server}/p4k/exception/{entry.Name}", content).Result)
									{
										if (errorReport.StatusCode == System.Net.HttpStatusCode.OK)
										{
											Console.WriteLine("This exception has been reported.");
										}
									}
								}
							}
						}
						catch (Exception)
						{
							Console.WriteLine("There was a problem whilst attempting to report this error.");
						}
					}
				}
			}
		}

19 Source : TreeExtractor.cs
with MIT License
from dolkensp

private async Task<Boolean> ExtractNodeAsync(IStreamTreeItem node, String outputRoot, ExtractModeEnum extractMode, String rootPath)
		{
			this._filesExtracted += 1;

			var forgeFactory = new DataForgeFormatFactory { };
			var cryxmlFactory = new CryXmlFormatFactory { };

			node = forgeFactory.Extract(node);
			node = cryxmlFactory.Extract(node);

			if (rootPath == null)
			{
				rootPath = Path.GetDirectoryName(node.RelativePath);
				outputRoot = Path.GetDirectoryName(outputRoot);
			}

			// Get file path relative to the preplaceded root
			var relativePath = node.RelativePath.RelativeTo(rootPath);
			var absolutePath = Path.Combine(outputRoot, relativePath);

			if (!String.IsNullOrWhiteSpace(absolutePath))
			{
				var target = new FileInfo(absolutePath);

				if (!target.Directory.Exists) target.Directory.Create();

				if (target.Exists)
				{
					switch (extractMode)
					{
						case ExtractModeEnum.New: return false;
						case ExtractModeEnum.NewOrLatest: if (target.LastWriteTimeUtc >= node.LastModifiedUtc) return false; break;
						case ExtractModeEnum.Overwrite: break;
					}
				}

				#region Dump Raw File

				try
				{

					using (var dataStream = node.Stream)
					{
						dataStream.Seek(0, SeekOrigin.Begin);

						using (FileStream fs = File.Create(absolutePath))
						{
							await dataStream.CopyToAsync(fs, 4096);
						}

						target.LastWriteTimeUtc = node.LastModifiedUtc;
					}
				}
				catch (ZStdException ex)
				{
					return false;
				}

				#endregion
			}

			return true;
		}

19 Source : FileHelper.cs
with Apache License 2.0
from donet5

public static void WriteFile(string strFilePath, string strValue)
        {
            System.IO.FileInfo oFile = new System.IO.FileInfo(strFilePath);
            if (!oFile.Directory.Exists)
                oFile.Directory.Create();
            if (!oFile.Exists)
                oFile.Create().Close();
            System.IO.StreamWriter oWrite = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
            oWrite.Write(strValue);
            oWrite.Flush();
            oWrite.Close();
        }

19 Source : FileHelper.cs
with Apache License 2.0
from donet5

public static void WriteFile(string strFilePath, string strValue, string charset)
        {
            System.IO.FileInfo oFile = new System.IO.FileInfo(strFilePath);
            if (!oFile.Directory.Exists)
                oFile.Directory.Create();
            if (!oFile.Exists)
                oFile.Create().Close();
            System.IO.StreamWriter oWrite = new StreamWriter(strFilePath, false, System.Text.Encoding.GetEncoding(charset));
            oWrite.Write(strValue);
            oWrite.Flush();
            oWrite.Close();
        }

19 Source : Utility.IO.cs
with MIT License
from DonnYep

public static void CreateFolder(string path, string folderName)
            {
                var fullPath = Path.Combine(path, folderName);
                var dir = new DirectoryInfo(fullPath);
                if (!dir.Exists)
                {
                    dir.Create();
                    Utility.Debug.LogInfo("Path:" + path + "Folder is created ");
                }
            }

19 Source : Utility.IO.cs
with MIT License
from DonnYep

public static void CreateFolder(string path)
            {
                var dir = new DirectoryInfo(path);
                if (!dir.Exists)
                {
                    dir.Create();
                    Utility.Debug.LogInfo("Path:" + path + "Folder is created");
                }
            }

19 Source : DirectorySvgConverter.cs
with MIT License
from dotnet-campus

public void Convert(DirectoryInfo sourceInfo, DirectoryInfo destInfo)
        {
            if (sourceInfo == null)
            {
                throw new ArgumentNullException("sourceInfo", 
                    "The source directory cannot be null (or Nothing).");
            }
            if (destInfo == null)
            {
                throw new ArgumentNullException("destInfo",
                    "The destination directory cannot be null (or Nothing).");
            }
            if (!sourceInfo.Exists)
            {
                throw new ArgumentException(
                    "The source directory must exists.", "sourceInfo");
            }

            _convertedCount = 0;
            _sourceDir      = sourceInfo;
            _destinationDir = destInfo;
            DirectorySecurity dirSecurity = null;
            if (_includeSecurity)
            {
                dirSecurity = sourceInfo.GetAccessControl();
            }
            if (!destInfo.Exists)
            {
                if (dirSecurity != null)
                {
                    destInfo.Create(dirSecurity);
                }
                else
                {
                    destInfo.Create();
                }
                destInfo.Attributes = sourceInfo.Attributes;
            }
            else
            {
                if (dirSecurity != null)
                {
                    destInfo.SetAccessControl(dirSecurity);
                }
            }

            this.ProcessConversion(_sourceDir, _destinationDir);
        }

19 Source : FileSvgReader.cs
with MIT License
from dotnet-campus

public DrawingGroup Read(string svgFileName, DirectoryInfo destinationDir)
        {
            _workingDir = destinationDir;

            if (_workingDir != null)
            {
                if (!_workingDir.Exists)
                {
                    _workingDir.Create();
                }
            }

            _imageFile = null;
            _xamlFile  = null;
            _zamlFile  = null;

            return this.Read(svgFileName);
        }

19 Source : FileSvgReader.cs
with MIT License
from dotnet-campus

public bool SaveImage(string fileName, DirectoryInfo imageFileDir, 
            ImageEncoderType encoderType)
        {
            if (imageFileDir == null)
            {
                return this.SaveImageFile(fileName, String.Empty, encoderType);
            }
            else
            {   
                if (!imageFileDir.Exists)
                {
                    imageFileDir.Create();
                }

                string outputExt = GetImageFileExtention(encoderType);

                string fileNameWithoutExt = Path.GetFileNameWithoutExtension(
                    fileName);

                string imageFileName = Path.Combine(imageFileDir.FullName,
                    fileNameWithoutExt + outputExt);

                return this.SaveImageFile(fileName, imageFileName, encoderType);
            }
        }

19 Source : DirectoryCopier.cs
with MIT License
from dotnet-campus

public int Copy(string sourceDir, string targetDir)
        {
            _copiedCount = 0;

            if (sourceDir == null)
            {
                throw new ArgumentNullException("sourceDir");
            }
            if (sourceDir.Length == 0)
            {
                throw new ArgumentException("sourceDir");
            }
            if (!Directory.Exists(sourceDir))
            {
                throw new InvalidOperationException();
            }

            if (targetDir == null)
            {
                throw new ArgumentNullException("targetDir");
            }
            if (targetDir.Length == 0)
            {
                throw new ArgumentException("targetDir");
            }
            
            if (String.Equals(sourceDir, targetDir, 
                StringComparison.CurrentCultureIgnoreCase))
            {
                throw new InvalidOperationException();
            }

            DirectoryInfo sourceInfo = new DirectoryInfo(sourceDir);
            DirectoryInfo targetInfo = new DirectoryInfo(targetDir);
            DirectorySecurity dirSecurity = null;
            if (_includeSecurity)
            {
                dirSecurity = sourceInfo.GetAccessControl();
            }
            if (!targetInfo.Exists)
            {
                if (dirSecurity != null)
                {
                    targetInfo.Create(dirSecurity);
                }
                else
                {
                    targetInfo.Create();
                }
                targetInfo.Attributes = sourceInfo.Attributes;
            }
            else
            {
                if (dirSecurity != null)
                {
                    targetInfo.SetAccessControl(dirSecurity);
                }
            }

            Copy(sourceInfo, targetInfo);

            return _copiedCount;
        }

19 Source : StudentsController.cs
with MIT License
from dotnet-labs

[HttpPost("{id:int}/forms")]
        [ProducesResponseType(typeof(StudentFormSubmissionResult), StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [RequestSizeLimit(long.MaxValue)]
        public async Task<ActionResult<StudentFormSubmissionResult>> SubmitForm(int id, [FromForm] StudentForm form)
        {
            _logger.LogInformation($"Validating the form#{form.FormId} for Student ID={id}");

            if (form.Courses == null || form.Courses.Length == 0)
            {
                return BadRequest("Please enter at least one course.");
            }

            if (form.StudentFile == null || form.StudentFile.Length < 1)
            {
                return BadRequest("The uploaded file is empty.");
            }

            if (Path.GetExtension(form.StudentFile.FileName) != ".pdf")
            {
                return BadRequest($"The uploaded file {form.StudentFile.Name} is not a PDF file.");
            }

            var filePath = Path.Combine(@"App_Data", $"{DateTime.Now:yyyyMMddHHmmss}.pdf");
            new FileInfo(filePath).Directory?.Create();
            await using (var stream = new FileStream(filePath, FileMode.Create))
            {
                _logger.LogInformation($"Saving file [{form.StudentFile.FileName}]");
                await form.StudentFile.CopyToAsync(stream);
                _logger.LogInformation($"\t The uploaded file is saved as [{filePath}].");
            }

            var result = new StudentFormSubmissionResult { FormId = form.FormId, StudentId = id, FileSize = form.StudentFile.Length };
            return CreatedAtAction(nameof(ViewForm), new { id, form.FormId }, result);
        }

See More Examples