System.IO.File.WriteAllText(string, string)

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

4279 Examples 7

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

internal static void writeAccountData()
        {
            Account[] accArray = new Account[AccountController.userAccounts.Count];
            for (int i = 0; i < AccountController.userAccounts.Count; i++)
            {
                UserAccount item = (UserAccount)AccountController.userAccounts[i];
                accArray[i] = new Account { username = item.username, preplacedword = item.preplacedword ,  desktopAuth  = item.desktopAuth };
            }
            string json = JsonConvert.SerializeObject(new jsonObject { count = accArray.Length, accounts = accArray });
            System.IO.File.WriteAllText(SAVE_FILE_NAME, json);
        }

19 Source : Settings.xaml.cs
with GNU General Public License v3.0
from 00000vish

public static void updateSettingFile()
    {
        string json = JsonConvert.SerializeObject(jsonSetting);
        System.IO.File.WriteAllText(SETTING_FILE, json);
    }

19 Source : RCEPControl.cs
with MIT License
from 0x0ade

[RCEndpoint(true, "/notes", "", "", "Admin Notes", "Get or set some administrative notes.")]
        public static void Notes(Frontend f, HttpRequestEventArgs c) {
            string path = Path.ChangeExtension(f.Settings.FilePath, ".notes.txt");
            string text;

            if (c.Request.HttpMethod == "POST") {
                try {
                    using (StreamReader sr = new(c.Request.InputStream, Encoding.UTF8, false, 1024, true))
                        text = sr.ReadToEnd();
                    File.WriteAllText(path, text);
                    f.RespondJSON(c, new {
                        Info = "Success."
                    });
                    return;
                } catch (Exception e) {
                    f.RespondJSON(c, new {
                        Error = e.ToString()
                    });
                    return;
                }
            }

            if (!File.Exists(path)) {
                f.Respond(c, "");
                return;
            }

            try {
                text = File.ReadAllText(path);
                f.Respond(c, text);
            } catch (Exception e) {
                f.RespondJSON(c, new {
                    Error = e.ToString()
                });
                return;
            }
        }

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

private static void Generate(string projDir, string relativePath, IReadOnlyList<NodeModel> model, Action<IReadOnlyList<NodeModel>, StringBuilder> generator)
        {
            var path = Path.Combine(projDir, relativePath);

            StringBuilder newContentBuilder = new StringBuilder();

            bool skip = false;
            foreach (var line in File.ReadLines(path))
            {
                if (line.Contains("//CodeGenEnd"))
                {
                    generator.Invoke(model, newContentBuilder);
                    skip = false;
                }

                if (!skip)
                {
                    newContentBuilder.AppendLine(line);
                }

                if (line.Contains("//CodeGenStart"))
                {
                    skip = true;
                }
            }

            File.WriteAllText(path, newContentBuilder.ToString());
        }

19 Source : ProxyGenerator.cs
with MIT License
from 1100100

public static List<Type> GenerateProxy(List<Type> interfaces)
        {
            if (interfaces.Any(p => !p.IsInterface && !typeof(IService).IsreplacedignableFrom(p)))
                throw new ArgumentException("The proxy object must be an interface and inherit IService.", nameof(interfaces));

            var replacedemblies = DependencyContext.Default.RuntimeLibraries.SelectMany(i => i.GetDefaultreplacedemblyNames(DependencyContext.Default).Select(z => replacedembly.Load(new replacedemblyName(z.Name)))).Where(i => !i.IsDynamic);

            var types = replacedemblies.Select(p => p.GetType()).Except(interfaces);
            replacedemblies = types.Aggregate(replacedemblies, (current, type) => current.Append(type.replacedembly));

            var trees = interfaces.Select(GenerateProxyTree).ToList();

            if (UraganoOptions.Output_DynamicProxy_SourceCode.Value)
            {
                for (var i = 0; i < trees.Count; i++)
                {
                    File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), $"{interfaces[i].Name}.Implement.cs"),
                        trees[i].ToString());
                }
            }

            using (var stream = CompileClientProxy(trees,
                replacedemblies.Select(x => MetadataReference.CreateFromFile(x.Location))
                    .Concat(new[]
                    {
                        MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().replacedembly.Location)
                    })))
            {
                var replacedembly = replacedemblyLoadContext.Default.LoadFromStream(stream);
                return replacedembly.GetExportedTypes().ToList();
            }
        }

19 Source : Core.cs
with MIT License
from 1y0n

public static bool Gen_C(string shellcode, string path, string execute, string inject, string arch, string detect)
        {
            string finalcode;
            shellcode = Shellcode_Handle(shellcode);
            shellcode = XOR_C("c", shellcode);

            Random r = new Random();
            int n = r.Next(0, Global.Company_name.Length - 1);
            string comname = Global.Company_name[n];

            string c_compile_info = C_Template.compile_info.Replace("{{companyname}}", comname);

            //图标设置
            if (Global.ICONPATH != "")
            {
                c_compile_info += @"IDI_ICON1 ICON ""{{path}}""";
                c_compile_info = c_compile_info.Replace("{{path}}", Global.ICONPATH.Replace("\\", "\\\\"));
            }
            System.IO.File.WriteAllText("C:\\Windows\\Temp\\Yanri_res.rc", c_compile_info);
            string res_cmd = "windres C:\\Windows\\Temp\\Yanri_res.rc C:\\Windows\\Temp\\Yanri_res.o";
            if (arch.StartsWith("32"))
            {
                res_cmd += " --target=pe-i386";
            }
            Common.Execute_Cmd(res_cmd);
            bool icon_set = System.IO.File.Exists("C:\\Windows\\Temp\\Yanri_res.o");
            //System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.rc");

            //根据执行方式选择代码模板
            if (execute == "执行4-Dynamic")
            {
                finalcode = C_Template.Dynamic.Replace("{{shellcode}}", shellcode);
            }
            else
            {
                finalcode = C_Template.Base_Code.Replace("{{shellcode}}", shellcode);
                switch (execute)
                {
                    case "执行1-VirtualAlloc":
                        finalcode = finalcode.Replace("//{{execute}}", C_Template.VirtualALloc);
                        break;
                    case "执行2-GetProcAddress":
                        finalcode = finalcode.Replace("//{{execute}}", C_Template.GetProcessAddress);
                        break;
                    case "注入现有进程":
                        finalcode = finalcode.Replace("//{{execute}}", C_Template.CreateRemoteThread);
                        finalcode = finalcode.Replace("{{pid}}", inject);
                        break;
                    case "注入新进程":
                        finalcode = finalcode.Replace("//{{execute}}", C_Template.CreateNew);
                        finalcode = finalcode.Replace("{{processname}}", inject);
                        break;
                    default:
                        return false;
                }
            }
            //虚拟机及沙箱检测
            switch (detect)
            {
                case "沙箱:延时约180秒":
                    finalcode = finalcode.Replace("//{{sanbox_vm_detect}}", C_Template.Super_Delay);
                    break;
                case "虚拟机:简单反虚拟机":
                    finalcode = finalcode.Replace("//{{sanbox_vm_detect}}", C_Template.Vm_Detect);
                    break;
            }

            //保存代码到临时文件
            string temp_path = @"C:\Windows\Temp\YANRI_TEMP_" + Common.GetRandomString(6, true, true, true, false, "") + ".c";
            System.IO.File.WriteAllText(temp_path, finalcode);

            //编译
            if (C_Compiler(arch, temp_path, path, icon_set))
            {
                //System.IO.File.Delete(temp_path);
                System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.o");
                return true;
            } else
            {
                System.IO.File.Delete(temp_path);
                System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.o");
                return false;
            }
        }

19 Source : Form1.cs
with Mozilla Public License 2.0
from 1M50RRY

private void button3_Click(object sender, EventArgs e)
        {
            //Crypt
            string result = Properties.Resources.stub;
            result = result.Replace("%startup%", startup.Checked.ToString().ToLower());
            result = result.Replace("%native%", native.Checked.ToString().ToLower());
            result = result.Replace("%selfinj%", si.Checked.ToString().ToLower());
            result = result.Replace("%antivm%", antivm.Checked.ToString().ToLower());
            result = result.Replace("%key%", key.Text);
            result = result.Replace("%asm%", GenerateKey());
            var providerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v4.0"}
            };
            CompilerResults results;
            using (var provider = new CSharpCodeProvider(providerOptions))
            {
                var Params = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, Environment.GetEnvironmentVariable("temp") + "\\Crypted.exe", true);
                if (ico !=  null)
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86 /win32icon:\"" + ico + "\"";
                else
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86";

                Params.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
                Params.Referencedreplacedemblies.Add("System.dll");
                Params.Referencedreplacedemblies.Add("System.Drawing.Dll");
                Params.Referencedreplacedemblies.Add("System.Security.Dll");
                Params.Referencedreplacedemblies.Add("System.Management.dll");

                string fname = "";
                if (punp.Checked)
                {
                    fname = Pump();
                    Params.EmbeddedResources.Add(fname); 
                }
                
                string tmp = "payload";
                File.WriteAllBytes(tmp, EncryptAES(encFile, key.Text));
                Params.EmbeddedResources.Add(tmp);
                results = provider.CompilereplacedemblyFromSource(Params, result);
                try
                {
                    File.Delete(tmp);
                    File.Delete(fname);
                }
                catch(Exception)
                {

                } 
            }
            if (results.Errors.Count == 0)
            {
                String temp = Environment.GetEnvironmentVariable("temp");
                if (obf.Checked)
                {
                   
                    File.WriteAllBytes(temp + "\\cli.exe", Properties.Resources.cli);
                    File.WriteAllBytes(temp + "\\Confuser.Core.dll", Properties.Resources.Confuser_Core);
                    File.WriteAllBytes(temp + "\\Confuser.DynCipher.dll", Properties.Resources.Confuser_DynCipher);
                    File.WriteAllBytes(temp + "\\Confuser.Protections.dll", Properties.Resources.Confuser_Protections);
                    File.WriteAllBytes(temp + "\\Confuser.Renamer.dll", Properties.Resources.Confuser_Renamer);
                    File.WriteAllBytes(temp + "\\Confuser.Runtime.dll", Properties.Resources.Confuser_Runtime);
                    File.WriteAllBytes(temp + "\\dnlib.dll", Properties.Resources.dnlib);

                    String crproj = Properties.Resources.def.Replace("%out%", Environment.CurrentDirectory);
                    crproj = crproj.Replace("%base%", temp);
                    crproj = crproj.Replace("%file%", temp + "\\Crypted.exe");
                    File.WriteAllText(temp + "\\def.crproj", crproj);

                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.Arguments = "/C " + temp + "\\cli.exe " + temp + "\\def.crproj";
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.CreateNoWindow = true;
                    startInfo.FileName = "cmd.exe";
                    Thread pr = new Thread(() => Process.Start(startInfo));
                    pr.Start();
                    pr.Join();
                }
                else
                {
                    String file = Environment.CurrentDirectory + "\\Crypted.exe";
                    try
                    {
                        File.Delete(file);
                    }
                    catch(Exception)
                    {

                    }
                    File.Move(temp + "\\Crypted.exe", file);
                }
                    

                MessageBox.Show("Done! Check Crypted.exe in the same folder.", "Crypting", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            
            foreach (CompilerError compilerError in results.Errors)
            {
                MessageBox.Show(string.Format("Error: {0}, At line {1}", compilerError.ErrorText, compilerError.Line));
            }
            
            
                
        }

19 Source : Core.cs
with MIT License
from 1y0n

public static bool Generate_1_IP(string arch, string ip, string port, string path)
        {
            string finalip = "";

            foreach (char c in ip)
            {
                finalip += "'" + c + "',";
            }
            finalip += @"'\0'";

            string FinalCode = T_EasyMode.GetCode().Replace("{{ip}}", finalip).Replace("{{port}}", port);

            string temp_path = @"C:\Windows\Temp\YANRI_TEMP_" + Common.GetRandomString(6, true, true, true, false, "") + ".c";
            System.IO.File.WriteAllText(temp_path, FinalCode);

            //开始编译
            string compilecmd = @"gcc " + temp_path + @" -o """ + path + @""" -mwindows -m"+ arch.Substring(0, 2) +" -lws2_32";

            if (!Common.Execute_Cmd(compilecmd).Contains("error:"))
            {
                System.IO.File.Delete(temp_path);
                return true;
            }
            else
            {
                System.IO.File.Delete(temp_path);
                return false;
            }
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

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



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

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


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

                     string path = string.Empty;

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

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

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

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

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

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

                                 plus.Append(sw.ToString());

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

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


        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

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

static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

                var arguments = new Dictionary<string, string>();
                foreach (var argument in args)
                {
                    var idx = argument.IndexOf(':');
                    if (idx > 0)
                        arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                    else
                        arguments[argument] = string.Empty;
                }

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    PrintError("[-] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/help"))
                {
                    help();
                }
                else if (arguments.Count < 3)
                {
                    PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.Count >= 3)
                {
                    string key = "SuperStrongKey";
                    string shellcode = null;
                    byte[] rawshellcode = new byte[] { };
                    if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
                        }
                        else
                        {
                            shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                        }

                    }
                    else if (arguments.ContainsKey("/url"))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = GetRawShellcode(arguments["/url"]);
                        }
                        else
                        {
                            shellcode = GetShellcode(arguments["/url"]);
                        }
                    }

                    if (shellcode != null || rawshellcode.Length > 0)
                    {

                        byte[] buf = new byte[] { };

                        if (arguments.ContainsKey("/key"))
                        {
                            key = (arguments["/key"]);
                        }
                        PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
                        if (arguments["/enc"] == "xor")
                        {
                            byte[] xorshellcode = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < xorshellcode.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", xorshellcode);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else if (arguments["/enc"] == "aes")
                        {
                            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
                            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
                            byte[] bytesEncrypted = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < bytesEncrypted.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else
                        {
                            PrintError("[-] Please specify correct encryption type.");
                        }
                    }
                    else
                    {
                        PrintError("[-] Please check the specified file path or the URL.");
                    }
                }
                else
                {
                    PrintError("[-] File doesn't exists. Please check the specified file path.");
                }
            }
            catch (Exception ex)
            {
                PrintError(ex.Message);
            }
        }

19 Source : Program.cs
with MIT License
from 5argon

static void Main(string[] args)
        {
            for (int i = 0; i < tag.Length; i++)
            {
                for (int j = 0; j < scd.Length; j++)
                {
                    Gen1(tag[i], scd[j]);
                }
            }
            File.WriteAllText("./EnreplacedyManagerUtilitySingleton.gen", sw.ToString());
        }

19 Source : ToolsService.cs
with Apache License 2.0
from 91270

public bool CreateDbContext(string strPath, string strSolutionName)
        {
            try
            {
                //获取数据库所有表
                var tables = Db.DbMaintenance.GetTableInfoList().Select(it => it.Name).ToList();

                #region 模板样式
                var clreplacedTemplate = $"" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"// <auto-generated>\r\n" +
                    $"//     此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。\r\n" +
                    $"//     如果重新生成代码,将覆盖对此文件的手动更改。\r\n" +
                    $"//     author MEIAM\r\n" +
                    $"// </auto-generated>\r\n" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"\r\n" +
                    $"using { strSolutionName }.Common;\r\n" +
                    $"using { strSolutionName }.Model;\r\n" +
                    $"using System.Diagnostics;\r\n" +
                    $"using System.Linq;\r\n" +
                    $"using SqlSugar;\r\n" +
                    $"using System;\r\n" +
                    $"\r\n" +
                    $"namespace { strSolutionName }.Core\r\n" +
                    $"{{\r\n" +
                    $"        /// <summary>\r\n" +
                    $"        /// 数据库上下文\r\n" +
                    $"        /// </summary>\r\n" +
                    $"    public clreplaced DbContext\r\n" +
                    $"    {{\r\n" +
                    $"\r\n" +
                    $"        public SqlSugarClient Db;   //用来处理事务多表查询和复杂的操作\r\n" +
                    $"\r\n" +
                    $"        public static SqlSugarClient Current\r\n" +
                    $"        {{\r\n" +
                    $"            get\r\n" +
                    $"            {{\r\n" +
                    $"                return new SqlSugarClient(new ConnectionConfig()\r\n" +
                    $"                {{\r\n" +
                    $"                    ConnectionString = AppSettings.Configuration[\"DbConnection:ConnectionString\"],\r\n" +
                    $"                    DbType = (DbType)Convert.ToInt32(AppSettings.Configuration[\"DbConnection:DbType\"]),\r\n" +
                    $"                    IsAutoCloseConnection = false,\r\n" +
                    $"                    IsShardSameThread = true,\r\n" +
                    $"                    InitKeyType = InitKeyType.Attribute,\r\n" +
                    $"                    ConfigureExternalServices = new ConfigureExternalServices()\r\n" +
                    $"                    {{\r\n" +
                    $"                        DataInfoCacheService = new RedisCache()\r\n" +
                    $"                    }},\r\n" +
                    $"                    MoreSettings = new ConnMoreSettings()\r\n" +
                    $"                    {{\r\n" +
                    $"                        IsAutoRemoveDataCache = true\r\n" +
                    $"                    }}\r\n" +
                    $"                }});\r\n" +
                    $"            }}\r\n" +
                    $"        }}\r\n" +
                    $"\r\n" +
                    $"        public DbContext()\r\n" +
                    $"        {{\r\n" +
                    $"            Db = new SqlSugarClient(new ConnectionConfig()\r\n" +
                    $"            {{\r\n" +
                    $"                ConnectionString = AppSettings.Configuration[\"DbConnection:ConnectionString\"],\r\n" +
                    $"                DbType = (DbType)Convert.ToInt32(AppSettings.Configuration[\"DbConnection:DbType\"]),\r\n" +
                    $"                IsAutoCloseConnection = true,\r\n" +
                    $"                IsShardSameThread = true,\r\n" +
                    $"                InitKeyType = InitKeyType.Attribute,\r\n" +
                    $"                ConfigureExternalServices = new ConfigureExternalServices()\r\n" +
                    $"                {{\r\n" +
                    $"                    DataInfoCacheService = new RedisCache()\r\n" +
                    $"                }},\r\n" +
                    $"                MoreSettings = new ConnMoreSettings()\r\n" +
                    $"                {{\r\n" +
                    $"                    IsAutoRemoveDataCache = true\r\n" +
                    $"                }}\r\n" +
                    $"            }});\r\n" +
                    $"            //调式代码 用来打印SQL \r\n" +
                    $"            Db.Aop.OnLogExecuting = (sql, pars) =>\r\n" +
                    $"            {{\r\n" +
                    $"                Debug.WriteLine(sql);\r\n" +
                    $"            }};\r\n" +
                    $"        }}\r\n" +
                    $"\r\n" +
                    $"        public DbSet<T> DbTable<T>() where T : clreplaced, new()\r\n" +
                    $"        {{\r\n" +
                    $"            return new DbSet<T>(Db);\r\n" +
                    $"        }}\r\n" +
                    $"\r\n";

                foreach (var table in tables)
                {
                    clreplacedTemplate = clreplacedTemplate + $"        public DbSet<{table}> {table.Replace("_", "")}Db => new DbSet<{table}>(Db);\r\n";
                };

                clreplacedTemplate = clreplacedTemplate +
                    $"\r\n" +
                    $"    }}\r\n" +
                    $"\r\n" +
                    $"    /// <summary>\r\n" +
                    $"    /// 扩展ORM\r\n" +
                    $"    /// </summary>\r\n" +
                    $"    public clreplaced DbSet<T> : SimpleClient<T> where T : clreplaced, new()\r\n" +
                    $"    {{\r\n" +
                    $"        public DbSet(SqlSugarClient context) : base(context)\r\n" +
                    $"        {{\r\n" +
                    $"\r\n" +
                    $"        }}\r\n" +
                    $"    }}\r\n" +
                    $"\r\n" +
                    $"}}\r\n";
                #endregion

                File.WriteAllText(strPath, clreplacedTemplate);

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

19 Source : ToolsService.cs
with Apache License 2.0
from 91270

public bool CreateIServices(string strPath, string strSolutionName, string tableName)
        {
            try
            {

                string saveFileName = $"I{tableName.Replace("_", "")}Service.cs";

                #region 遍历子目录查找相同IService

                List<string> sourecFiles = new List<string>();

                GetFiles(strPath, sourecFiles);

                string readFilePath = sourecFiles.FirstOrDefault(m => m.Contains(saveFileName));

                string value = "";

                if (!string.IsNullOrEmpty(readFilePath))
                {
                    value = GetCustomValue(File.ReadAllText(readFilePath), "#region CustomInterface \r\n", "        #endregion");
                }

                #endregion

                #region 模板样式
                var clreplacedTemplate = $"" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"// <auto-generated>\r\n" +
                    $"//     此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。\r\n" +
                    $"//     如果重新生成代码,将覆盖对此文件的手动更改。\r\n" +
                    $"//     author MEIAM\r\n" +
                    $"// </auto-generated>\r\n" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"using { strSolutionName }.Model;\r\n" +
                    $"using { strSolutionName }.Model.Dto;\r\n" +
                    $"using { strSolutionName }.Model.View;\r\n" +
                    $"using System.Collections.Generic;\r\n" +
                    $"using System.Threading.Tasks;\r\n" +
                    $"using SqlSugar;\r\n" +
                    $"using System.Linq;\r\n" +
                    $"using System;\r\n" +
                    $"\r\n" +
                    $"namespace { strSolutionName }.Interfaces\r\n" +
                    $"{{\r\n" +
                    $"    public interface I{tableName.Replace("_", "")}Service : IBaseService<{tableName}>\r\n" +
                    $"    {{\r\n" +
                    $"\r\n" +
                    $"        #region CustomInterface \r\n" +
                    $"{(string.IsNullOrWhiteSpace(value) ? "" : value)}" +
                    $"        #endregion\r\n" +
                    $"\r\n" +
                    $"    }}\r\n" +
                    $"}}\r\n";
                #endregion

                File.WriteAllText($"{ strPath }\\{ saveFileName }", clreplacedTemplate);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

19 Source : ToolsService.cs
with Apache License 2.0
from 91270

public bool CreateServices(string strPath, string strSolutionName, string tableName)
        {
            try
            {

                string saveFileName = $"{tableName.Replace("_", "")}Service.cs";

                #region 遍历子目录查找相同IService

                List<string> sourecFiles = new List<string>();

                GetFiles(strPath, sourecFiles);

                string readFilePath = sourecFiles.FirstOrDefault(m => m.Contains(saveFileName));

                string value = "";

                if (!string.IsNullOrEmpty(readFilePath))
                {
                    value = GetCustomValue(File.ReadAllText(readFilePath), "#region CustomInterface \r\n", "        #endregion\r\n");
                }

                #endregion

                #region 模板样式
                var clreplacedTemplate = $"" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"// <auto-generated>\r\n" +
                    $"//     此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。\r\n" +
                    $"//     如果重新生成代码,将覆盖对此文件的手动更改。\r\n" +
                    $"//     author MEIAM\r\n" +
                    $"// </auto-generated>\r\n" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"using { strSolutionName }.Model;\r\n" +
                    $"using { strSolutionName }.Model.Dto;\r\n" +
                    $"using { strSolutionName }.Model.View;\r\n" +
                    $"using System.Collections.Generic;\r\n" +
                    $"using System.Threading.Tasks;\r\n" +
                    $"using SqlSugar;\r\n" +
                    $"using System.Linq;\r\n" +
                    $"using System;\r\n" +
                    $"\r\n" +
                    $"namespace { strSolutionName }.Interfaces\r\n" +
                    $"{{\r\n" +
                    $"    public clreplaced {tableName.Replace("_", "")}Service : BaseService<{tableName}>, I{tableName.Replace("_", "")}Service\r\n" +
                    $"    {{\r\n" +
                    $"\r\n" +
                    $"        public {tableName.Replace("_", "")}Service(IUnitOfWork unitOfWork) : base(unitOfWork)\r\n" +
                    $"        {{\r\n" +
                    $"        }}\r\n" +
                    $"\r\n" +
                    $"        #region CustomInterface \r\n" +
                    $"{(string.IsNullOrWhiteSpace(value) ? "" : value)}" +
                    $"        #endregion\r\n" +
                    $"\r\n" +
                    $"    }}\r\n" +
                    $"}}\r\n";
                #endregion

                File.WriteAllText($"{ strPath }\\{saveFileName}", clreplacedTemplate);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

19 Source : Manga.cs
with GNU General Public License v3.0
from 9vult

public void SaveSettings(string lang, string group, string overrideName)
        {
            Logger.Log("Saving settings for manga '" + name + "'");
            if (File.Exists(mangaDirectory.FullName + "\\settings"))
            {
                File.WriteAllText(mangaDirectory.FullName + "\\settings", String.Empty);
                File.WriteAllText(mangaDirectory.FullName + "\\settings", lang + "|" + group + "|" + overrideName);
            }
        }

19 Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult

public void AddManga(string api, string num, bool isUpdate)
        {
            string json;
            if (api != null)
            {
                using (var wc = new System.Net.WebClient())
                {
                    json = wc.DownloadString(api);
                }
            }
            else
            {
                json = File.ReadAllText(homeFolder + "\\" + num + "\\manga.json");
            }

            // Deserialize the JSON file
            dynamic contents = JsonConvert.DeserializeObject(json);
            string mangaName = contents.manga.replacedle;
            string mangaDirectory = homeFolder + "\\" + num;

            if (!Directory.Exists(mangaDirectory))
            {
                Logger.Log("Creating directory '" + mangaDirectory + "' and related files");
                Directory.CreateDirectory(mangaDirectory);
                File.WriteAllText(mangaDirectory + "\\manga.json", json); // Write the JSON to a file
                File.WriteAllText(mangaDirectory + "\\tracker", "1|1"); // Write initial tracking info to a file
            }
            File.WriteAllText(mangaDirectory + "\\downloading", ""); // Create "Downloading" file

            Manga m = new Manga(mangaName, new DirectoryInfo(mangaDirectory), "1", "1");

            if (!isUpdate)
            {
                DialogResult result = new FrmMangaSettings(m).ShowDialog();
                MessageBox.Show("Downloading data...\nYou may close the Browser as you desire.");
            }
            m.LoadSettings();
            downloadManager.AddMDToQueue(m, contents.chapter, isUpdate);
            RefreshContents();
        }

19 Source : KissManga.cs
with GNU General Public License v3.0
from 9vult

public override void _Create(string mangaUrl)
        {
            id = mangaUrl;
            string replacedle = KissMangaHelper.GetName(mangaUrl);
            string lang_code = "gb"; // Not that it matters for KissManga

            FileHelper.CreateFolder(FileHelper.APP_ROOT, KissMangaHelper.GetUrlName(mangaUrl));

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "kissmanga",
                Id = KissMangaHelper.GetUrlName(mangaUrl),
                Name = replacedle,
                LangCode = lang_code,
                Group = "^any-group",
                UserName = replacedle,
                Chapter = "1",
                Page = "1",
                Latest = "1"
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);

            _Load(false);
            GetSetPrunedChapters(true);
        }

19 Source : KissManga.cs
with GNU General Public License v3.0
from 9vult

public override void Save(string chapter, string page)
        {
            this.currentchapter = chapter;
            this.currentpage = page;

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "kissmanga",
                Id = mangaRoot.Name,
                Name = name,
                LangCode = userlang,
                Group = usergroup,
                UserName = userreplacedle,
                Chapter = chapter,
                Page = page,
                Latest = lastchapter
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);
        }

19 Source : MangaDex.cs
with GNU General Public License v3.0
from 9vult

public override void _Create(string mangaUrl)
        {
            id = mangaUrl;
            string jsonText = MangaDexHelper.GetMangaJSON(mangaUrl);

            JObject jobj = JObject.Parse(jsonText);
            string replacedle = (string)jobj["manga"]["replacedle"];

            string lang_code = "gb";

            FileHelper.CreateFolder(FileHelper.APP_ROOT, MangaDexHelper.GetMangaID(mangaUrl));

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "mangadex",
                Id = MangaDexHelper.GetMangaID(mangaUrl),
                Name = replacedle,
                LangCode = lang_code,
                Group = "^any-group",
                UserName = replacedle,
                Chapter = "1",
                Page = "1",
                Latest = "1"
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);            

            _Load(false);
            GetSetPrunedChapters(true);
        }

19 Source : MangaDex.cs
with GNU General Public License v3.0
from 9vult

public override void Save(string chapter, string page)
        {
            this.currentchapter = chapter;
            this.currentpage = page;

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "mangadex",
                Id = mangaRoot.Name,
                Name = name,
                LangCode = userlang,
                Group = usergroup,
                UserName = userreplacedle,
                Chapter = chapter,
                Page = page,
                Latest = lastchapter
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);
        }

19 Source : Nhentai.cs
with GNU General Public License v3.0
from 9vult

public override void _Create(string mangaUrl)
        {
            FileHelper.CreateFolder(FileHelper.APP_ROOT, "h" + id);

            MangaInfo info = new MangaInfo()
            {
                Type = "hentai",
                Source = "nhentai",
                Id = id,
                Name = name,
                UserName = userreplacedle,
                Chapter = "1",
                Page = "1"
            };

            string output = JsonConvert.SerializeObject(info);            
            File.WriteAllText(Path.Combine(hentaiRoot.FullName, "manga.json"), output);

            DirectoryInfo chapDir = FileHelper.CreateFolder(hentaiRoot, "1");
            chapters.Add(new Chapter(chapDir, id, "1", true));

            _Load();
        }

19 Source : Nhentai.cs
with GNU General Public License v3.0
from 9vult

public override void Save(string chapter, string page)
        {
            this.currentchapter = chapter;
            this.currentpage = page;

            MangaInfo info = new MangaInfo()
            {
                Type = "hentai",
                Source = "nhentai",
                Id = hentaiRoot.Name,
                Name = name,
                UserName = userreplacedle,
                Chapter = chapter,
                Page = page
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(hentaiRoot.FullName, "manga.json"), output);
        }

19 Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult

public void AddHentai(string chapterID, string replacedle)
        {
            string hentaiDirectory = homeFolder + "\\h" + chapterID;

            if (!Directory.Exists(hentaiDirectory))
            {
                Logger.Log("Creating directory '" + hentaiDirectory + "' and related files");
                Directory.CreateDirectory(hentaiDirectory);
                File.WriteAllText(hentaiDirectory + "\\tracker", "1|1"); // Write initial tracking info to a file
                File.WriteAllText(hentaiDirectory + "\\replacedle", replacedle); // Write the replacedle to a file
            }
            File.WriteAllText(hentaiDirectory + "\\downloading", ""); // Create "Downloading" file

            Manga m = new Manga("", new DirectoryInfo(hentaiDirectory), "1", "1");
            DialogResult r = new FrmHentaiSettings(m).ShowDialog();

            MessageBox.Show("Downloading data...\nYou may close the Browser as you desire.");

            downloadManager.AddNHToQueue(m, chapterID);
            RefreshContents();
        }

19 Source : FrmDoublePageReader.cs
with GNU General Public License v3.0
from 9vult

private void FrmReader_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (File.Exists(root.FullName + "\\tracker"))
            {
                File.WriteAllText(root.FullName + "\\tracker", String.Empty);
                File.WriteAllText(root.FullName + "\\tracker", cmboChapter.SelectedItem.ToString() + "|" + cmboPage.SelectedItem.ToString());
            }
            startPage.RefreshContents();
        }

19 Source : Program.cs
with MIT License
from a1xd

static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = (Exception)e.ExceptionObject;
            System.IO.File.WriteAllText("error.log", ex.ToString());
            MessageBox.Show(ex.Message, "Error");
        }

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

public static void Terminate()
        {
            TerminateSignal = true;

            if (AllowFileDebugging != 0 || MessageBox.Show("The internal debugger reports that the log contents are greater than 500kB, the log" +
                $" file size is estimated to be {DumpText.Length / 1000}kB, would you like to save the log file?", "Large File Warning",
                MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
                File.WriteAllText($"dump-{DateTime.Now.Ticks}.log", DumpText);

            Environment.Exit(0);
        }

19 Source : FileUtils.cs
with Apache License 2.0
from A7ocin

public static void WriteAllText(string path, string content)
		{
			System.IO.File.WriteAllText(path, content);
		}

19 Source : obfuscator.cs
with MIT License
from aaaddress1

public static bool obfuscaAsm(string asmPath, string outObfAsmPath)
        {
            label_extra_count = 0;
            junk_count = 0;
            obfuscat_code_count = 0;

            string asmCode = System.IO.File.ReadAllText(asmPath);

            string[] gadgets = asmCode.Split('\n');
            string fixCode = "";
            string extCode = ".section	.text$junk,\x22wx\x22\n";

            string currFuncNameMatch = "";
            for (int i = 0; i < gadgets.Length; i++)
            {
                Program.mainUi.BeginInvoke((MethodInvoker)delegate () { Program.mainUi.percntLB.Text = (i * 100 / gadgets.Length) + "%"; });
                var currLine = gadgets[i];

                Match m = new Regex(@"(.+):\r").Match(gadgets[i]);
                if (m.Success && i < gadgets.Length - 2)
                {
                    currFuncNameMatch = m.Groups[1].Value;
                    if (gadgets[i + 2].Contains("cfi_startproc"))
                    {
                        logMsg("found func::" + currFuncNameMatch + "() at #" + i, Color.Blue);
                        fixCode += gadgets[i] + "\n\r" + gadgets[i + 1] + "\n\r" + gadgets[i + 2] + "\n\r";
                        i += 2;
                        continue;
                    }
                    else currFuncNameMatch = "";
                }

                if (currFuncNameMatch != "")
                {
                    string getJunk = "", getExtra = "";
                    if (Properties.Settings.Default.cnfseCode)
                    {
                        obfuscatCode(gadgets[i], ref getJunk, ref getExtra);
                        fixCode += getJunk;
                        extCode += getExtra;
                    }
                    else
                        fixCode += gadgets[i] + "\n\r";

                    getJunk = ""; getExtra = "";
                    if (Properties.Settings.Default.insrtJunk)
                    {
                        randJunk(ref getJunk, ref getExtra);
                        fixCode += getJunk;
                        extCode += getExtra;
                        if (gadgets[i].Contains("cfi_endproc")) currFuncNameMatch = "";
                    }
                }
                else
                    fixCode += gadgets[i] + "\n\r";
            }
            Program.mainUi.BeginInvoke((MethodInvoker)delegate () { Program.mainUi.percntLB.Text = "100%"; });
            logMsg(string.Format(
                "[\tOK\t] obfuscate result:         \n" +
                " - generate {0} junk codes         \n" +
                " - generate {1} obfuscated codes   \n" +
                " - generate {2} function pieces    \n", junk_count, obfuscat_code_count, label_extra_count), Color.Green);

            System.IO.File.WriteAllText(outObfAsmPath, fixCode + "\n" + extCode);
            return true;
        }

19 Source : GameSaveLoadInMem.cs
with Apache License 2.0
from AantCoder

[HarmonyPrefix]
		public static bool Prefix(ScribeSaver __instance, string filePath, string doreplacedentElementName)
		{
			if (!Enable) return true;

			Loger.Log("ScribeSaver_InitSaving_Patch Start");
			var that = Traverse.Create(__instance);

			if (Scribe.mode != 0)
			{
				Log.Error("Called InitSaving() but current mode is " + Scribe.mode);
				Scribe.ForceStop();
			}
			if (that.Field("curPath").GetValue<string>() != null)
			{
				Log.Error("Current path is not null in InitSaving");
				that.Field("curPath").SetValue(null);
				that.Field("savedNodes").GetValue<HashSet<string>>().Clear();
				that.Field("nextListElementTemporaryId").SetValue(0);
			}
			try
			{
				Scribe.mode = LoadSaveMode.Saving;
				var saveStream = SaveData = new MemoryStream();
				//var saveStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
				File.WriteAllText(filePath, "Online save");
				that.Field("saveStream").SetValue(saveStream);

				XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
				xmlWriterSettings.Indent = true;
				xmlWriterSettings.IndentChars = "\t";
				var writer = XmlWriter.Create(saveStream, xmlWriterSettings);
				that.Field("writer").SetValue(writer);

				writer.WriteStartDoreplacedent();
				__instance.EnterNode(doreplacedentElementName);
			}
			catch (Exception ex)
			{
				Log.Error("Exception while init saving file: " + filePath + "\n" + ex);
				__instance.ForceStop();
				throw;
			}
			Loger.Log("ScribeSaver_InitSaving_Patch End");
			return false;
		}

19 Source : FileChecker.cs
with Apache License 2.0
from AantCoder

public static byte[] CreateListFolder(string directory)
        {
            var dirs = Directory.GetDirectories(directory).OrderBy(x => x);
            var sb = new StringBuilder();
            foreach (var dir in dirs)
            {
                // только для дебага, а то папка Online city каждый раз обновляется

                var di = new DirectoryInfo(dir);
#if DEBUG
                if (di.Name.Equals("OnlineCity"))
                    continue;
#endif
                sb.AppendLine(di.Name);
            }

            var txt = sb.ToString();
            var diRoot = new DirectoryInfo(directory);
            File.WriteAllText(Path.Combine(Loger.PathLog, diRoot.Name + ".txt"), txt);
            return Encoding.ASCII.GetBytes(txt);
        }

19 Source : MixedRealityStandardShaderGUI.cs
with Apache License 2.0
from abist-co-ltd

[MenuItem("Mixed Reality Toolkit/Utilities/Upgrade MRTK Standard Shader for Lightweight Render Pipeline")]
        protected static void UpgradeShaderForLightweightRenderPipeline()
        {
            if (EditorUtility.DisplayDialog("Upgrade MRTK Standard Shader?", 
                                            "This will alter the MRTK Standard Shader for use with Unity's Lightweight Render Pipeline. You cannot undo this action.", 
                                            "Ok", 
                                            "Cancel"))
            {
                string path = replacedetDatabase.GetreplacedetPath(StandardShaderUtility.MrtkStandardShader);

                if (!string.IsNullOrEmpty(path))
                {
                    try
                    {
                        string upgradedShader = File.ReadAllText(path);
                        upgradedShader = upgradedShader.Replace("Tags{ \"RenderType\" = \"Opaque\" \"LightMode\" = \"ForwardBase\" }",
                                                                "Tags{ \"RenderType\" = \"Opaque\" \"LightMode\" = \"LightweightForward\" }");
                        upgradedShader = upgradedShader.Replace("//#define _LIGHTWEIGHT_RENDER_PIPELINE",
                                                                "#define _LIGHTWEIGHT_RENDER_PIPELINE");
                        File.WriteAllText(path, upgradedShader);
                        replacedetDatabase.Refresh();

                        Debug.LogFormat("Upgraded {0} for use with the Lightweight Render Pipeline.", path);
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                }
                else
                {
                    Debug.LogErrorFormat("Failed to get replacedet path to: {0}", StandardShaderUtility.MrtkStandardShaderName);
                }
            }
        }

19 Source : OVRGradleGeneration.cs
with MIT License
from absurd-joy

public void OnPostGenerateGradleAndroidProject(string path)
	{
		UnityEngine.Debug.Log("OVRGradleGeneration triggered.");

		var targetOculusPlatform = new List<string>();
		if (OVRDeviceSelector.isTargetDeviceQuest)
		{
			targetOculusPlatform.Add("quest");
		}
		OVRPlugin.AddCustomMetadata("target_oculus_platform", String.Join("_", targetOculusPlatform.ToArray()));
		UnityEngine.Debug.LogFormat("Quest = {0}", OVRDeviceSelector.isTargetDeviceQuest);

#if UNITY_2019_3_OR_NEWER
		string gradleBuildPath = Path.Combine(path, "../launcher/build.gradle");
#else
		string gradleBuildPath = Path.Combine(path, "build.gradle");
#endif
		bool v2SigningEnabled = true;

		if (File.Exists(gradleBuildPath))
		{
			try
			{
				string gradle = File.ReadAllText(gradleBuildPath);
				int v2Signingindex = gradle.IndexOf("v2SigningEnabled false");

				if (v2Signingindex != -1)
				{
					//v2 Signing flag found, ensure the correct value is set based on platform.
					if (v2SigningEnabled)
					{
						gradle = gradle.Replace("v2SigningEnabled false", "v2SigningEnabled true");
						System.IO.File.WriteAllText(gradleBuildPath, gradle);
					}
				}
				else
				{
					//v2 Signing flag missing, add it right after the key store preplacedword and set the value based on platform.
					int keyPreplacedIndex = gradle.IndexOf("keyPreplacedword");
					if (keyPreplacedIndex != -1)
					{
						int v2Index = gradle.IndexOf("\n", keyPreplacedIndex) + 1;
						if(v2Index != -1)
						{
							gradle = gradle.Insert(v2Index, "v2SigningEnabled " + (v2SigningEnabled ? "true" : "false") + "\n");
							System.IO.File.WriteAllText(gradleBuildPath, gradle);
						}
					}
				}
			}
			catch (System.Exception e)
			{
				UnityEngine.Debug.LogWarningFormat("Unable to overwrite build.gradle, error {0}", e.Message);
			}
		}
		else
		{
			UnityEngine.Debug.LogWarning("Unable to locate build.gradle");
		}

		PatchAndroidManifest(path);
	}

19 Source : AndroidVideoEditorUtil.cs
with MIT License
from absurd-joy

[MenuItem("Oculus/Video/Enable Native Android Video Player")]
    public static void EnableNativeVideoPlayer()
    {
        // rename NativeJavaPlayer.java.DISABLED to NativeJavaPlayer.java
        if (File.Exists(disabledPlayerFileName))
        {
            File.Move(disabledPlayerFileName, videoPlayerFileName);
            File.Move(disabledPlayerFileName + ".meta", videoPlayerFileName + ".meta");
        }

        replacedetDatabase.Importreplacedet(videoPlayerFileName);
        replacedetDatabase.Deletereplacedet(disabledPlayerFileName);

        // Enable audio plugins
        PluginImporter audio360 = (PluginImporter)replacedetImporter.GetAtPath(audio360PluginPath);
        PluginImporter audio360exo29 = (PluginImporter)replacedetImporter.GetAtPath(audio360Exo29PluginPath);

        if (audio360 != null && audio360exo29 != null)
        {
            audio360.SetCompatibleWithPlatform(BuildTarget.Android, true);
            audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, true);
            audio360.SaveAndReimport();
            audio360exo29.SaveAndReimport();
        }

        // Enable gradle build with exoplayer
        EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;

        // create android plugins directory if it doesn't exist
        if (!Directory.Exists(androidPluginsFolder))
        {
            Directory.CreateDirectory(androidPluginsFolder);
        }

        if (!File.Exists(gradleTemplatePath))
        {
            if (File.Exists(gradleTemplatePath + ".DISABLED"))
            {
                File.Move(disabledGradleTemplatePath, gradleTemplatePath);
                File.Move(disabledGradleTemplatePath + ".meta", gradleTemplatePath+".meta");
            }
            else
            {
                File.Copy(internalGradleTemplatePath, gradleTemplatePath);
            }
            replacedetDatabase.Importreplacedet(gradleTemplatePath);
        }

        // parse the gradle file to check the current version:
        string currentFile = File.ReadAllText(gradleTemplatePath);

        List<string> lines = new List<string>(currentFile.Split('\n'));

        var gradleVersion = new System.Text.RegularExpressions.Regex("com.android.tools.build:gradle:([0-9]+\\.[0-9]+\\.[0-9]+)").Match(currentFile).Groups[1].Value;

        if (gradleVersion == "2.3.0")
        {
            // add google() to buildscript/repositories
            int buildscriptRepositories = GoToSection("buildscript.repositories", lines);

            if (FindInScope("google\\(\\)", buildscriptRepositories + 1, lines) == -1)
            {
                lines.Insert(GetScopeEnd(buildscriptRepositories + 1, lines), "\t\tgoogle()");
            }

            // add google() and jcenter() to allprojects/repositories
            int allprojectsRepositories = GoToSection("allprojects.repositories", lines);

            if (FindInScope("google\\(\\)", allprojectsRepositories + 1, lines) == -1)
            {
                lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tgoogle()");
            }
            if (FindInScope("jcenter\\(\\)", allprojectsRepositories + 1, lines) == -1)
            {
                lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tjcenter()");
            }
        }

        // add "compile 'com.google.android.exoplayer:exoplayer:2.9.5'" to dependencies
        int dependencies = GoToSection("dependencies", lines);
        if (FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines) == -1)
        {
            lines.Insert(GetScopeEnd(dependencies + 1, lines), "\tcompile 'com.google.android.exoplayer:exoplayer:2.9.5'");
        }

        int android = GoToSection("android", lines);

        // add compileOptions to add Java 1.8 compatibility
        if (FindInScope("compileOptions", android + 1, lines) == -1)
        {
            int compileOptionsIndex = GetScopeEnd(android + 1, lines);
            lines.Insert(compileOptionsIndex, "\t}");
            lines.Insert(compileOptionsIndex, "\t\ttargetCompatibility JavaVersion.VERSION_1_8");
            lines.Insert(compileOptionsIndex, "\t\tsourceCompatibility JavaVersion.VERSION_1_8");
            lines.Insert(compileOptionsIndex, "\tcompileOptions {");
        }

        // add sourceSets if Version < 2018.2
#if !UNITY_2018_2_OR_NEWER

        if (FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines) == -1)
        {
            lines.Insert(GetScopeEnd(android + 1, lines), "\tsourceSets.main.java.srcDir \"" + gradleSourceSetPath + "\"");
        }
#endif

        File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray()));
    }

19 Source : AndroidVideoEditorUtil.cs
with MIT License
from absurd-joy

[MenuItem("Oculus/Video/Disable Native Android Video Player")]
    public static void DisableNativeVideoPlayer()
    {
        if (File.Exists(videoPlayerFileName))
        {
            File.Move(videoPlayerFileName, disabledPlayerFileName);
            File.Move(videoPlayerFileName + ".meta", disabledPlayerFileName + ".meta");
        }

        replacedetDatabase.Importreplacedet(disabledPlayerFileName);
        replacedetDatabase.Deletereplacedet(videoPlayerFileName);

        // Disable audio plugins
        PluginImporter audio360 = (PluginImporter)replacedetImporter.GetAtPath(audio360PluginPath);
        PluginImporter audio360exo29 = (PluginImporter)replacedetImporter.GetAtPath(audio360Exo29PluginPath);

        if (audio360 != null && audio360exo29 != null)
        {
            audio360.SetCompatibleWithPlatform(BuildTarget.Android, false);
            audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, false);
            audio360.SaveAndReimport();
            audio360exo29.SaveAndReimport();
        }

        // remove exoplayer and sourcesets from gradle file (leave other parts since they are harmless).
        if (File.Exists(gradleTemplatePath))
        {
            // parse the gradle file to check the current version:
            string currentFile = File.ReadAllText(gradleTemplatePath);

            List<string> lines = new List<string>(currentFile.Split('\n'));

            int dependencies = GoToSection("dependencies", lines);
            int exoplayer = FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines);
            if (exoplayer != -1)
            {
                lines.RemoveAt(exoplayer);
            }

            int android = GoToSection("android", lines);
            int sourceSets = FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines);
            if (sourceSets != -1)
            {
                lines.RemoveAt(sourceSets);
            }

            File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray()));
        }
    }

19 Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware

public static void ExportExampleToHtml(Example example, bool isUniqueExport = true)
        {
            if (isUniqueExport)
            {
                if (!GetPathForExport())
                {
                    MessageBox.Show("Bad path. Please, try export once more.");
                    return;
                }
            }

            var replacedembly = typeof (HtmlExportHelper).replacedembly;

            string[] names = replacedembly.GetManifestResourceNames();

            var templateFile = names.SingleOrDefault(x => x.Contains(TemplateFileName));

            using (var s = replacedembly.GetManifestResourceStream(templateFile))
            using (var sr = new StreamReader(s))
            {
                string lines = sr.ReadToEnd();

                var exampleFolderPath = ExportPath;//string.Format("{0}{1}\\", ExportPath, example.replacedle);
                //CreateExampleFolder(exampleFolderPath);

                PrintMainWindow("scichart-wpf-chart-example-" + example.replacedle.ToLower().Replace(" ", "-"), exampleFolderPath);
                
                lines = ReplaceTagsWithExample(lines, example);
                var fileName = string.Format("wpf-{0}chart-example-{1}.html",                    
                    example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
                    example.replacedle.ToLower().Replace(" ", "-"));

                File.WriteAllText(Path.Combine(ExportPath, fileName), lines);
            }
            
        }

19 Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware

private static void ExportIndexToHtml(IModule module)
        {
            var replacedembly = typeof(HtmlExportHelper).replacedembly;

            string[] names = replacedembly.GetManifestResourceNames();

            var templateFile = names.SingleOrDefault(x => x.Contains(IndexTemplateFileName));

            using (var s = replacedembly.GetManifestResourceStream(templateFile))
            using (var sr = new StreamReader(s))
            {
                string lines = sr.ReadToEnd();

                StringBuilder sb = new StringBuilder();
                foreach (var categoryGroup in module.Examples.Values.GroupBy(x => x.TopLevelCategory))
                {
                    sb.Append("<h2>").Append(categoryGroup.Key).Append("</h2>").Append(Environment.NewLine);

                    foreach (var exampleGroup in categoryGroup.GroupBy(x => x.Group))
                    {
                        sb.Append("<h4>").Append(exampleGroup.Key).Append("</h4>").Append(Environment.NewLine);
                        sb.Append("<ul>").Append(Environment.NewLine);
                        foreach (var example in exampleGroup)
                        {
                            var fileName = string.Format("wpf-{0}chart-example-{1}",
                                example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
                                example.replacedle.ToLower().Replace(" ", "-"));
                            sb.Append("<li>").Append("<a href=\"").Append(fileName).Append("\">").Append(example.replacedle).Append("</a></li>");
                        }
                        sb.Append("</ul>").Append(Environment.NewLine);
                    }                    
                }
                lines = lines.Replace("[Index]", sb.ToString());

                File.WriteAllText(Path.Combine(ExportPath, "wpf-chart-examples.html"), lines);
            }
        }

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

private async Task GetGooglePlusUserData(string accessToken)
        {
            try
            {
                HttpClient client = new HttpClient();
                var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;

                client.CancelPendingRequests();
                HttpResponseMessage output = await client.GetAsync(urlProfile);

                if (output.IsSuccessStatusCode)
                {                  
                    string outputData = await output.Content.ReadreplacedtringAsync();
                    GoogleUserData newUserData = JsonConvert.DeserializeObject<GoogleUserData>(outputData);

                    if (newUserData != null)
                    {                                                
                        string file = Utils.GetDataStoreFolder() + newUserData.id;
                        string jsonFile = file + ".json";
                        string imageFile = file + ".png";

                        if (File.Exists(jsonFile))
                        {
                            string json = File.ReadAllText(jsonFile);
                            GoogleUserData existingUserData = JsonConvert.DeserializeObject<GoogleUserData>(json);
                            if (newUserData.picture != null &&
                                (!File.Exists(imageFile) ||
                                 existingUserData.picture != null && existingUserData.picture != newUserData.picture))
                                Utils.GetImage(newUserData.picture, imageFile);
                        }
                        else
                            Utils.GetImage(newUserData.picture, imageFile);

                        // overwrites existing file
                        File.WriteAllText(jsonFile, outputData);

                        _userData = newUserData;
                    }
                }
            }
            catch (Exception)
            {
                // return some rubbish for now.
                _userData = new GoogleUserData() { id = "1234567890", name = "Unknown" };
            }
        }

19 Source : Host.cs
with MIT License
from acandylevey

public void GenerateManifest(string description, string[] allowedOrigins, bool overwrite = false)
        {
            if (File.Exists(ManifestPath) && !overwrite)
            {
                Log.LogMessage("Manifest exists already");
            }
            else
            {
                Log.LogMessage("Generating Manifest");

                string manifest = JsonConvert.SerializeObject(new Manifest(Hostname, description, Utils.replacedemblyExecuteablePath(), allowedOrigins));
                File.WriteAllText(ManifestPath, manifest);

                Log.LogMessage("Manifest Generated");
            }
        }

19 Source : DataRepository.cs
with MIT License
from Accelerider

private static void WriteToLocal(string path, string contents)
        {
            try
            {
                File.WriteAllText(path, contents);
            }
            catch (IOException)
            {
                WriteToLocal(path, contents);
            }
        }

19 Source : DefaultLogger.cs
with MIT License
from Accelerider

private void Write(string category, string message, Exception e)
        {
            message = $"{message}{Environment.NewLine}";

            if (e != null)
            {
                message = $"{message}{e.Message}{Environment.NewLine}" +
                          $"{e.StackTrace}{Environment.NewLine}";
            }

            message = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} " +
                      $"[{Thread.CurrentThread.ManagedThreadId}] " +
                      $"{category.ToUpper()} " +
                      $"{_type.FullName}{Environment.NewLine}" +
                      $"{message}{Environment.NewLine}";

            System.Diagnostics.Debug.Write(message);
            File.WriteAllText(
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "accelerider.windows.log"),
                message);
        }

19 Source : LootGenerationFactory_Test.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string TestLootGen(int numItems, int tier, bool logStats, string displayTable)
        {
            string displayHeader = $"\n LootFactory Simulator - Items\n ---------------------\n";

            Console.WriteLine($"Creating {numItems} items, that are in tier {tier}");

            var lootStats = new LootStats(logStats);

            // Create a dummy treasure profile for preplaceding in tier value
            TreasureDeath profile = new TreasureDeath
            {
                Tier = tier,
                LootQualityMod = 0
            };

            // Loop depending on how many items you are creating
            for (int i = 0; i < numItems; i++)
            {
                var tesreplacedem = LootGenerationFactory.CreateRandomLootObjects(profile, true);
                lootStats.AddItem(tesreplacedem, logStats);
            }

            var displayStats = BuildDisplayStats(lootStats, displayTable);

            Console.WriteLine(displayHeader);
            Console.WriteLine(displayStats);

            displayHeader += $" A total of {lootStats.TotalItems} items were generated in Tier {tier}. \n";

            if (logStats)
            {
                string myfilename = string.Format("LootSim-{0:hh-mm-ss-tt_MM-dd-yyyy}.csv", DateTime.Now);
                File.WriteAllText(myfilename, displayHeader + displayStats);
            }

            return displayHeader;
        }

19 Source : LootGenerationFactory_Test.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string TestLootGenMonster(uint deathTreasureDID, int numCorpses, bool logStats, string displayTable)
        {
            string displayHeader = $"\n LootFactory Simulator - Corpses\n ---------------------\n";

            var corpseContainer = new List<WorldObject>();
            var ls = new LootStats(logStats);

            Console.WriteLine($"Creating {numCorpses} corpses.");

            var deathTreasure = DatabaseManager.World.GetCachedDeathTreasure(deathTreasureDID);
            if (deathTreasure != null)
            {
                displayHeader += $" Loot profile {deathTreasure.Id} (a Tier {deathTreasure.Tier} profile) from DID {deathTreasureDID} was used for creating {numCorpses} corpses. \n";
            }
            else
            {
                displayHeader += $" DID {deathTreasureDID} you specified is invalid. \n";
                return displayHeader;
            }

            for (int i = 0; i < numCorpses; i++)
            {
                if (deathTreasure != null)
                {
                    corpseContainer = LootGenerationFactory.CreateRandomLootObjects(deathTreasure);

                    if (corpseContainer.Count < ls.MinItemsCreated)
                        ls.MinItemsCreated = corpseContainer.Count;
                    if (corpseContainer.Count > ls.MaxItemsCreated)
                        ls.MaxItemsCreated = corpseContainer.Count;

                    foreach (var looreplacedem in corpseContainer)
                        ls.AddItem(looreplacedem, logStats);
                }
            }

            var displayStats = BuildDisplayStats(ls, displayTable);

            Console.WriteLine(displayHeader);
            Console.WriteLine(displayStats);

            displayHeader += $" A total of {ls.TotalItems} unique items were generated. \n";

            if (logStats)
            {
                string myfilename = $"LootSim_DeathTreasureDID-{deathTreasureDID}" + string.Format("_{0:hh-mm-ss-tt_MM-dd-yyyy}.csv", DateTime.Now);
                File.WriteAllText(myfilename, displayHeader + displayStats);
            }

            return displayHeader;
        }

19 Source : RunScriptViewModel.cs
with GNU Lesser General Public License v3.0
from acnicholas

public void SaveScratch()
        {
            var s = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var p = Path.Combine(s, "SCaddins");
            if (!Directory.Exists(p)) {
                Directory.CreateDirectory(p);
            }
            File.WriteAllText(Path.Combine(p, "Script.cs"), Script);
        }

19 Source : ProjectFolderTests.cs
with MIT License
from action-bi-toolkit

[Fact]
        public void Removes_base_folder_if_no_files_have_been_written()
        {
            var baseDir = Path.Combine(TestFolder.Path, "Test");
            Directory.CreateDirectory(baseDir);

            File.WriteAllText(Path.Combine(baseDir, "test.txt"), "...");

            // BEFORE
            replacedert.True(Directory.Exists(baseDir));

            using (var root = new ProjectRootFolder(baseDir))
            {
                // Do nothing (not writing any files)

                root.Commit();
            }

            // AFTER
            replacedert.False(Directory.Exists(baseDir));
            // this will have removed 'test.txt'
        }

19 Source : RunScriptViewModel.cs
with GNU Lesser General Public License v3.0
from acnicholas

public void Save()
        {
            if (CanSave)
            {
                File.WriteAllText(currentFileName, Script);
            }
            else
            {
                SaveAs();
            }
        }

19 Source : SelfUpdater.cs
with MIT License
from actions

private string GenerateUpdateScript(bool restartInteractiveRunner)
        {
            int processId = Process.GetCurrentProcess().Id;
            string updateLog = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Diag), $"SelfUpdate-{DateTime.UtcNow.ToString("yyyyMMdd-HHmmss")}.log");
            string runnerRoot = HostContext.GetDirectory(WellKnownDirectory.Root);

#if OS_WINDOWS
            string templateName = "update.cmd.template";
#else
            string templateName = "update.sh.template";
#endif

            string templatePath = Path.Combine(runnerRoot, $"bin.{_targetPackage.Version}", templateName);
            string template = File.ReadAllText(templatePath);

            template = template.Replace("_PROCESS_ID_", processId.ToString());
            template = template.Replace("_RUNNER_PROCESS_NAME_", $"Runner.Listener{IOUtil.ExeExtension}");
            template = template.Replace("_ROOT_FOLDER_", runnerRoot);
            template = template.Replace("_EXIST_RUNNER_VERSION_", BuildConstants.RunnerPackage.Version);
            template = template.Replace("_DOWNLOAD_RUNNER_VERSION_", _targetPackage.Version);
            template = template.Replace("_UPDATE_LOG_", updateLog);
            template = template.Replace("_RESTART_INTERACTIVE_RUNNER_", restartInteractiveRunner ? "1" : "0");

#if OS_WINDOWS
            string scriptName = "_update.cmd";
#else
            string scriptName = "_update.sh";
#endif

            string updateScript = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), scriptName);
            if (File.Exists(updateScript))
            {
                IOUtil.DeleteFile(updateScript);
            }

            File.WriteAllText(updateScript, template);
            return updateScript;
        }

19 Source : GitSourceProvider.cs
with MIT License
from actions

private async Task RemoveGitConfig(RunnerActionPluginExecutionContext executionContext, GitCliManager gitCommandManager, string targetPath, string configKey, string configValue)
        {
            int exitCode_configUnset = await gitCommandManager.GitConfigUnset(executionContext, targetPath, configKey);
            if (exitCode_configUnset != 0)
            {
                // if unable to use git.exe unset http.extraheader or core.askpreplaced, modify git config file on disk. make sure we don't left credential.
                if (!string.IsNullOrEmpty(configValue))
                {
                    executionContext.Warning("An unsuccessful attempt was made using git command line to remove \"http.extraheader\" from the git config. Attempting to modify the git config file directly to remove the credential.");
                    string gitConfig = Path.Combine(targetPath, ".git/config");
                    if (File.Exists(gitConfig))
                    {
                        string gitConfigContent = File.ReadAllText(Path.Combine(targetPath, ".git", "config"));
                        if (gitConfigContent.Contains(configKey))
                        {
                            string setting = $"extraheader = {configValue}";
                            gitConfigContent = Regex.Replace(gitConfigContent, setting, string.Empty, RegexOptions.IgnoreCase);

                            setting = $"askpreplaced = {configValue}";
                            gitConfigContent = Regex.Replace(gitConfigContent, setting, string.Empty, RegexOptions.IgnoreCase);

                            File.WriteAllText(gitConfig, gitConfigContent);
                        }
                    }
                }
                else
                {
                    executionContext.Warning($"Unable to remove \"{configKey}\" from the git config. To remove the credential, execute \"git config --unset - all {configKey}\" from the repository root \"{targetPath}\".");
                }
            }
        }

19 Source : IOUtilL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DeletesDirectoryReparsePointChain()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/<guid 1> -> <guid 2>
                //   randomDir/<guid 2> -> <guid 3>
                //   randomDir/<guid 3> -> <guid 4>
                //   randomDir/<guid 4> -> <guid 5>
                //   randomDir/<guid 5> -> targetDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //
                // The purpose of this test is to verify that DirectoryNotFoundException is gracefully handled when
                // deleting a chain of reparse point directories. Since the reparse points are named in a random order,
                // the DirectoryNotFoundException case is likely to be encountered.
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string linkDir1 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir1");
                    string linkDir2 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir2");
                    string linkDir3 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir3");
                    string linkDir4 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir4");
                    string linkDir5 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir5");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir1, target: linkDir2);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir2, target: linkDir3);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir3, target: linkDir4);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir4, target: linkDir5);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir5, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir1));
                    replacedert.True(new DirectoryInfo(linkDir1).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir1, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(randomDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(linkDir1));
                    replacedert.False(Directory.Exists(targetDir));
                    replacedert.False(File.Exists(file));
                    replacedert.False(Directory.Exists(randomDir));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 Source : IOUtilL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteFile_DeletesFile()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string file = Path.Combine(directory, "some file");
                try
                {
                    Directory.CreateDirectory(directory);
                    File.WriteAllText(path: file, contents: "some contents");

                    // Act.
                    IOUtil.DeleteFile(file);

                    // replacedert.
                    replacedert.False(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

See More Examples