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

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

1422 Examples 7

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

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

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

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

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

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

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

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

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

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

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

static void Repack(string input, string[] extras, string output, string name = null) {
            Console.Error.WriteLine($"Repacking: {input} -> {output}");
            if (name == null)
                name = Path.GetFileName(output);

            string outputTmp = Path.Combine(Path.GetDirectoryName(output), name);
            if (File.Exists(outputTmp))
                File.Delete(outputTmp);

            List<string> args = new List<string>();
            args.Add($"/out:{outputTmp}");
            args.Add(input);
            foreach (string dep in extras)
                if (!string.IsNullOrWhiteSpace(dep))
                    args.Add(dep.Trim());

            RepackOptions options = new RepackOptions(args);
            ILRepack repack = new ILRepack(options);
            repack.Repack();

            if (output != outputTmp) {
                if (File.Exists(output))
                    File.Delete(output);
                File.Move(outputTmp, output);
            }
        }

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

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

19 View Source File : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 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 View Source File : UpdateHandle.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public void UpdateGeoFile(string geoName, Config config, Action<bool, string> update)
        {
            _config = config;
            _updateFunc = update;
            var url = string.Format(geoUrl, geoName);

            DownloadHandle downloadHandle = null;
            if (downloadHandle == null)
            {
                downloadHandle = new DownloadHandle();

                downloadHandle.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        _updateFunc(false, string.Format(UIRes.I18N("MsgDownloadGeoFileSuccessfully"), geoName));

                        try
                        {
                            string fileName = Utils.GetPath(Utils.GetDownloadFileName(url));
                            if (File.Exists(fileName))
                            {
                                string targetPath = Utils.GetPath($"{geoName}.dat");
                                if (File.Exists(targetPath))
                                {
                                    File.Delete(targetPath);
                                }
                                File.Move(fileName, targetPath);
                                _updateFunc(true, "");
                            }
                        }
                        catch (Exception ex)
                        {
                            _updateFunc(false, ex.Message);
                        }
                    }
                    else
                    {
                        _updateFunc(false, args.Msg);
                    }
                };
                downloadHandle.Error += (sender2, args) =>
                {
                    _updateFunc(false, args.GetException().Message);
                };
            }

            askToDownload(downloadHandle, url, false);
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                Process[] existing = Process.GetProcessesByName("v2rayN");
                foreach (Process p in existing)
                {
                    string path = p.MainModule.FileName;
                    if (path == GetPath("v2rayN.exe"))
                    {
                        p.Kill();
                        p.WaitForExit(100);
                    }
                }
            }
            catch (Exception ex)
            {
                // Access may be denied without admin right. The user may not be an administrator.
                showWarn("Failed to close v2rayN(关闭v2rayN失败).\n" +
                    "Close it manually, or the upgrade may fail.(请手动关闭正在运行的v2rayN,否则可能升级失败。\n\n" + ex.StackTrace);
            }

            StringBuilder sb = new StringBuilder();
            try
            {
                if (!File.Exists(fileName))
                {
                    if (File.Exists(defaultFilename))
                    {
                        fileName = defaultFilename;
                    }
                    else
                    {
                        showWarn("Upgrade Failed, File Not Exist(升级失败,文件不存在).");
                        return;
                    }
                }

                string thisAppOldFile = Application.ExecutablePath + ".tmp";
                File.Delete(thisAppOldFile);
                string startKey = "v2rayN/";


                using (ZipArchive archive = ZipFile.OpenRead(fileName))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        try
                        {
                            if (entry.Length == 0)
                            {
                                continue;
                            }
                            string fullName = entry.FullName;
                            if (fullName.StartsWith(startKey))
                            {
                                fullName = fullName.Substring(startKey.Length, fullName.Length - startKey.Length);
                            }
                            if (Application.ExecutablePath.ToLower() == GetPath(fullName).ToLower())
                            {
                                File.Move(Application.ExecutablePath, thisAppOldFile);
                            }

                            string entryOuputPath = GetPath(fullName);

                            FileInfo fileInfo = new FileInfo(entryOuputPath);
                            fileInfo.Directory.Create();
                            entry.ExtractToFile(entryOuputPath, true);
                        }
                        catch (Exception ex)
                        {
                            sb.Append(ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                showWarn("Upgrade Failed(升级失败)." + ex.StackTrace);
                return;
            }
            if (sb.Length > 0)
            {
                showWarn("Upgrade Failed,Hold ctrl + c to copy to clipboard.\n" +
                    "(升级失败,按住ctrl+c可以复制到剪贴板)." + sb.ToString());
                return;
            }

            Process.Start("v2rayN.exe");
            MessageBox.Show("Upgrade successed(升级成功)", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Close();
        }

19 View Source File : BuildUtil.cs
License : MIT License
Project Creator : 404Lcc

[InitializeOnLoadMethod]
        public static void BuildHotfix()
        {
            if (File.Exists("replacedets/Hotfix/Unity.Hotfix.asmdef~"))
            {
                File.Move("replacedets/Hotfix/Unity.Hotfix.asmdef~", "replacedets/Hotfix/Unity.Hotfix.asmdef");
                LogUtil.Log("安装Hotfix");
                replacedetDatabase.Refresh();
            }
            else
            {
                if (File.Exists("replacedets/Hotfix/Unity.Hotfix.asmdef"))
                {
                    LogUtil.Log("安装Hotfix");
                }
                else
                {
                    LogUtil.Log("Hotfix丢失");
                }
            }
            if (File.Exists("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes"))
            {
                File.Delete("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes");
            }
            if (File.Exists("replacedets/Resources/DLL/Unity.Hotfix.pdb.bytes"))
            {
                File.Delete("replacedets/Resources/DLL/Unity.Hotfix.pdb.bytes");
            }
            if (File.Exists("replacedets/Bundles/DLL/Unity.Hotfix.dll.bytes"))
            {
                File.Delete("replacedets/Bundles/DLL/Unity.Hotfix.dll.bytes");
            }
            if (File.Exists("replacedets/Bundles/DLL/Unity.Hotfix.pdb.bytes"))
            {
                File.Delete("replacedets/Bundles/DLL/Unity.Hotfix.pdb.bytes");
            }
#if Release
            if (File.Exists("Unity.Hotfix.csproj"))
            {
                RoslynUtil.BuildDll("Unity.Hotfix.csproj", "replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", BuildType.Release, false);
                FileUtil.Savereplacedet("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", RijndaelUtil.RijndaelEncrypt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", FileUtil.Getreplacedet("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes")));
                File.Copy("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", "replacedets/Bundles/DLL/Unity.Hotfix.dll.bytes", true);
            }
#else
            if (File.Exists("Library/Scriptreplacedemblies/Unity.Hotfix.dll") && File.Exists("Library/Scriptreplacedemblies/Unity.Hotfix.pdb"))
            {
                File.Copy("Library/Scriptreplacedemblies/Unity.Hotfix.dll", "replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", true);
                File.Copy("Library/Scriptreplacedemblies/Unity.Hotfix.pdb", "replacedets/Resources/DLL/Unity.Hotfix.pdb.bytes", true);
                FileUtil.Savereplacedet("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", RijndaelUtil.RijndaelEncrypt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", FileUtil.Getreplacedet("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes")));
                File.Copy("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", "replacedets/Bundles/DLL/Unity.Hotfix.dll.bytes", true);
                File.Copy("replacedets/Resources/DLL/Unity.Hotfix.pdb.bytes", "replacedets/Bundles/DLL/Unity.Hotfix.pdb.bytes", true);
            }
#endif
            LinkUtil.BuildLink();
            replacedetDatabase.Refresh();
        }

19 View Source File : AssetBundleManager.cs
License : MIT License
Project Creator : 404Lcc

public void CheckreplacedetsComplete()
        {
            Message?.Invoke("检测资源完整性");
            replacedetBundle replacedetBundle = replacedetBundle.LoadFromFile($"{PathUtil.GetPath(PathType.PersistentDataPath, "Res", PathUtil.GetPlatformForreplacedetBundle())}/{PathUtil.GetPlatformForreplacedetBundle()}");
            replacedetBundleManifest = replacedetBundle.Loadreplacedet<replacedetBundleManifest>("replacedetBundleManifest");
            replacedetBundle.Unload(false);
            List<string> replacedetBundleNameList = new List<string>();
            checkCount = localreplacedetBundleConfig.replacedetBundleDataDict.Count;
            foreach (KeyValuePair<string, replacedetBundleData> item in localreplacedetBundleConfig.replacedetBundleDataDict)
            {
                if (!File.Exists($"{PathUtil.GetPath(PathType.PersistentDataPath, "Res", PathUtil.GetPlatformForreplacedetBundle())}/{item.Key}.unity3d"))
                {
                    replacedetBundleNameList.Add(item.Key);
                    continue;
                }
                else if (new FileInfo($"{PathUtil.GetPath(PathType.PersistentDataPath, "Res", PathUtil.GetPlatformForreplacedetBundle())}/{item.Key}.unity3d").Length != item.Value.fileSize)
                {
                    replacedetBundleNameList.Add(item.Key);
                    continue;
                }
                else if (localreplacedetBundleConfig.replacedetBundleDataDict[item.Key].replacedetBundleHash != replacedetBundleManifest.GetreplacedetBundleHash($"{item.Key}.unity3d").ToString())
                {
                    replacedetBundleNameList.Add(item.Key);
                    continue;
                }
                currentCheckCount += 1;
                CheckProgress?.Invoke(currentCheckCount, checkCount);
            }
            if (replacedetBundleNameList.Count == 0)
            {
                if (isDownload)
                {
                    File.Move($"{PathUtil.GetPath(PathType.PersistentDataPath, "Res", PathUtil.GetPlatformForreplacedetBundle())}/ServerreplacedetBundleConfig.json", $"{PathUtil.GetPath(PathType.PersistentDataPath, "Res", PathUtil.GetPlatformForreplacedetBundle())}/replacedetBundleConfig.json");
                }
                Complete?.Invoke();
            }
            else
            {
                Error?.Invoke(null, "资源不完整");
            }
        }

19 View Source File : DownloadFile.cs
License : MIT License
Project Creator : 404Lcc

public bool Downloading()
        {
            if (File.Exists(downloadData.path))
            {
                currentSize = downloadData.size;
                return true;
            }
            long position = 0;
            string tempPath = downloadData.path + ".temp";
            if (File.Exists(tempPath))
            {
                using (FileStream fileStream = new FileStream(tempPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    position = fileStream.Length;
                    fileStream.Seek(position, SeekOrigin.Current);
                    if (position == downloadData.size)
                    {
                        if (File.Exists(downloadData.path))
                        {
                            File.Delete(downloadData.path);
                        }
                        File.Move(tempPath, downloadData.path);
                        currentSize = position;
                        return true;
                    }
                }
            }
            else
            {
                PathUtil.GetPath(PathType.PersistentDataPath, Path.GetDirectoryName(downloadData.path));
                using (FileStream fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    HttpWebRequest httpWebRequest = null;
                    HttpWebResponse httpWebResponse = null;
                    try
                    {
                        httpWebRequest = (HttpWebRequest)WebRequest.Create(downloadData.url);
                        httpWebRequest.ReadWriteTimeout = readWriteTimeout;
                        httpWebRequest.Timeout = timeout;
                        if (position > 0)
                        {
                            httpWebRequest.AddRange((int)position);
                        }
                        httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                        using (Stream stream = httpWebResponse.GetResponseStream())
                        {
                            stream.ReadTimeout = timeout;
                            long currentSize = position;
                            byte[] bytes = new byte[fileReadLength];
                            int readSize = stream.Read(bytes, 0, fileReadLength);
                            while (readSize > 0)
                            {
                                fileStream.Write(bytes, 0, readSize);
                                currentSize += readSize;
                                if (currentSize == downloadData.size)
                                {
                                    if (File.Exists(downloadData.path))
                                    {
                                        File.Delete(downloadData.path);
                                    }
                                    File.Move(tempPath, downloadData.path);
                                }
                                this.currentSize = currentSize;
                                readSize = stream.Read(bytes, 0, fileReadLength);
                            }
                        }
                    }
                    catch
                    {
                        if (File.Exists(tempPath))
                        {
                            File.Delete(tempPath);
                        }
                        if (File.Exists(downloadData.path))
                        {
                            File.Delete(downloadData.path);
                        }
                        state = DownloadState.Error;
                        error = "文件下载失败";
                    }
                    finally
                    {
                        if (httpWebRequest != null)
                        {
                            httpWebRequest.Abort();
                            httpWebRequest = null;
                        }
                        if (httpWebResponse != null)
                        {
                            httpWebResponse.Dispose();
                            httpWebResponse = null;
                        }
                    }
                }
            }
            if (state == DownloadState.Error)
            {
                return false;
            }
            return true;
        }

19 View Source File : PreprocessUtil.cs
License : MIT License
Project Creator : 404Lcc

public void OnPreprocessBuild(BuildReport report)
        {
            if (File.Exists("replacedets/Hotfix/Unity.Hotfix.asmdef"))
            {
                File.Move("replacedets/Hotfix/Unity.Hotfix.asmdef", "replacedets/Hotfix/Unity.Hotfix.asmdef~");
                LogUtil.Log("卸载Hotfix");
                replacedetDatabase.Refresh();
            }
            else
            {
                if (File.Exists("replacedets/Hotfix/Unity.Hotfix.asmdef~"))
                {
                    LogUtil.Log("卸载Hotfix");
                }
                else
                {
                    LogUtil.Log("Hotfix丢失");
                }
            }
        }

19 View Source File : PreprocessUtil.cs
License : MIT License
Project Creator : 404Lcc

public void OnPostprocessBuild(BuildReport report)
        {
            if (File.Exists("replacedets/Hotfix/Unity.Hotfix.asmdef~"))
            {
                File.Move("replacedets/Hotfix/Unity.Hotfix.asmdef~", "replacedets/Hotfix/Unity.Hotfix.asmdef");
                LogUtil.Log("安装Hotfix");
                replacedetDatabase.Refresh();
            }
            else
            {
                if (File.Exists("replacedets/Hotfix/Unity.Hotfix.asmdef"))
                {
                    LogUtil.Log("安装Hotfix");
                }
                else
                {
                    LogUtil.Log("Hotfix丢失");
                }
            }
        }

19 View Source File : SerializeHelper.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void SaveGlobalSettings(object data)
        {
            var settings = data;

            if (settings is null)
                return;

            //Log("Saving Global Settings");

            if (File.Exists(GLOBAL_FILE_DIR + ".bak"))
            {
                File.Delete(GLOBAL_FILE_DIR + ".bak");
            }

            if (File.Exists(GLOBAL_FILE_DIR))
            {
                File.Move(GLOBAL_FILE_DIR, GLOBAL_FILE_DIR + ".bak");
            }

            using (FileStream fileStream = File.Create(GLOBAL_FILE_DIR))
            {
                using (var writer = new StreamWriter(fileStream))
                {
                    try
                    {
                        writer.Write
                        (
                            JsonConvert.SerializeObject
                            (
                                settings,
                                Formatting.Indented,
                                new JsonSerializerSettings
                                {
                                    TypeNameHandling = TypeNameHandling.Auto,
                                }
                            )
                        );
                    }
                    catch (Exception e)
                    {
                        LogError(e);
                    }
                }
            }

            

            
        }

19 View Source File : RepositorySaveData.cs
License : Apache License 2.0
Project Creator : 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 View Source File : RepositorySaveData.cs
License : Apache License 2.0
Project Creator : AantCoder

public void DeletePlayerData(string login)
        {
            var pFiles = GetListPlayerFiles(login);

            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]);
        }

19 View Source File : RepositorySaveData.cs
License : Apache License 2.0
Project Creator : AantCoder

private List<string> GetListPlayerFiles(string login)
        {
            var result = new List<string>();
            var fileNameBase = GetFileNameBase(login);

            for (int num = 1; num <= CountSaveDataPlayer; num++)
            {
                if (!File.Exists(fileNameBase + num.ToString())) break;
                result.Add(fileNameBase + num.ToString());
            }
            if (result.Count == 0 && File.Exists(fileNameBase))
            {
                File.Move(fileNameBase, fileNameBase + "1");
                result.Add(fileNameBase + "1");
            }
            return result;
        }

19 View Source File : Repository.cs
License : Apache License 2.0
Project Creator : AantCoder

public void Save(bool onlyChangeData = false)
        {
            if (onlyChangeData && !ChangeData) return;
            Loger.Log("Server Saving");

            try
            {
                if (File.Exists(SaveFileName))
                {
                    if (File.Exists(SaveFileName + ".bak")) File.Delete(SaveFileName + ".bak");
                    File.Move(SaveFileName, SaveFileName + ".bak");
                }

                Data.MaxIdChat = ChatManager.Instance.MaxChatId;

                using (var fs = File.OpenWrite(SaveFileName))
                {
                    var bf = new BinaryFormatter();
                    bf.Serialize(fs, Data);
                }

                ChangeData = false;
            }
            catch
            {
                if (File.Exists(SaveFileName + ".bak"))
                    File.Copy(SaveFileName + ".bak", SaveFileName, true);
                throw;
            }

            Loger.Log("Server Saved");
        }

19 View Source File : AndroidVideoEditorUtil.cs
License : MIT License
Project Creator : 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 View Source File : AndroidVideoEditorUtil.cs
License : MIT License
Project Creator : 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 View Source File : OVRExpansionFileGenerator.cs
License : MIT License
Project Creator : absurd-joy

[MenuItem("Oculus/Tools/Build Mobile-Quest Expansion File", false, 100000)]
	public static void BuildBundles()
	{
		// Create expansion file directory and call build replacedet bundles
		string path = Application.dataPath + "/../replacedet Bundles/";
		if (!System.IO.Directory.Exists(path))
		{
			System.IO.Directory.CreateDirectory(path);
		}
		BuildPipeline.BuildreplacedetBundles(path, BuildreplacedetBundleOptions.ChunkBasedCompression, BuildTarget.Android);

		// Rename replacedet bundle file to the proper obb string
		if (File.Exists(path + "replacedet Bundles"))
		{
			string expansionName = "main." + PlayerSettings.Android.bundleVersionCode + "." + PlayerSettings.applicationIdentifier + ".obb";
			try
			{
				if (File.Exists(path + expansionName))
				{
					File.Delete(path + expansionName);
				}
				File.Move(path + "replacedet Bundles", path + expansionName);
				UnityEngine.Debug.Log("OBB expansion file " + expansionName + " has been successfully created at " + path);

				UpdateAndroidManifest();
			}
			catch (Exception e)
			{
				UnityEngine.Debug.LogError(e.Message);
			}
		}
	}

19 View Source File : OVRDirectorySyncer.cs
License : MIT License
Project Creator : absurd-joy

private void MoveRelevantFilesToTarget(SyncResult syncResult, CancellationToken cancellationToken)
	{
		// step 3: we move all new files to target
		var newFiles = syncResult.Created.Union(syncResult.Updated);
		foreach (var fileName in newFiles)
		{
			var sourceFileName = Path.Combine(Source, fileName);
			var destFileName = Path.Combine(Target, fileName);
			// target directory exists due to step CreateRelevantDirectoriesAtTarget()
			File.Move(sourceFileName, destFileName);
			cancellationToken.ThrowIfCancellationRequested();
		}
	}

19 View Source File : ONSPAudioPluginUpdater.cs
License : MIT License
Project Creator : absurd-joy

private static bool RenameSpatializerPluginToOld(string currentPluginPath)
    {
        if (File.Exists(currentPluginPath))
        {
            int index = 0;
            string targetPluginPath;
            string targetPluginMetaPath;
            for (; ; )
            {
                targetPluginPath = currentPluginPath + ".old" + index.ToString();
                targetPluginMetaPath = targetPluginPath + ".meta";
                if (!File.Exists(targetPluginPath) && !File.Exists(targetPluginPath))
                    break;
                ++index;
            }
            try
            {
                File.Move(currentPluginPath, targetPluginPath);
                File.Move(currentPluginPath + ".meta", targetPluginMetaPath);
                UnityEngine.Debug.LogFormat("Spatializer plugin renamed: {0} to {1}", currentPluginPath, targetPluginPath);
                return true;
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogWarningFormat("Unable to rename spatializer plugin: {0}, exception {1}", currentPluginPath, e.Message);
                return false;
            }
        }
        return false;
    }

19 View Source File : ONSPAudioPluginUpdater.cs
License : MIT License
Project Creator : absurd-joy

private static void AttemptSpatializerPluginUpdate(bool triggeredByAutoUpdate)
    {
        // We use a simplified path to update spatializer plugins:
        // If there is a new AudioPluginOculusSpatializer.dll.new, we'll rename the original one to .old, and the new one to .dll, and restart the editor

        string pluginsPath = GetSpatializerPluginsRootPath();
        string newX86PluginPath = Path.GetFullPath(Path.Combine(pluginsPath, "x86/AudioPluginOculusSpatializer.dll.new"));
        string newX64PluginPath = Path.GetFullPath(Path.Combine(pluginsPath, "x86_64/AudioPluginOculusSpatializer.dll.new"));
        if (File.Exists(newX86PluginPath) || File.Exists(newX64PluginPath))
        {
            bool userAcceptsUpdate = false;

            if (unityRunningInBatchmode)
            {
                userAcceptsUpdate = true;
            }
            else
            {
                int dialogResult = EditorUtility.DisplayDialogComplex("Update Spatializer Plugins",
                    "New spatializer plugin found. Do you want to upgrade? If you choose 'Upgrade', the old plugin will be renamed to AudioPluginOculusSpatializer.old",
                    "Upgrade", "Don't upgrade", "Delete new plugin");
                if (dialogResult == 0)
                {
                    userAcceptsUpdate = true;
                }
                else if (dialogResult == 1)
                {
                    // do nothing
                }
                else if (dialogResult == 2)
                {
                    try
                    {
                        File.Delete(newX86PluginPath);
                        File.Delete(newX86PluginPath + ".meta");
                        File.Delete(newX64PluginPath);
                        File.Delete(newX64PluginPath + ".meta");
                    }
                    catch (Exception e) 
                    {
                        UnityEngine.Debug.LogWarning("Exception happened when deleting new spatializer plugin: " + e.Message);
                    }
                }
            }

            if (userAcceptsUpdate)
            {
                bool upgradeDone = false;
                string curX86PluginPath = Path.Combine(pluginsPath, "x86/AudioPluginOculusSpatializer.dll");
                if (File.Exists(newX86PluginPath))
                {
                    RenameSpatializerPluginToOld(curX86PluginPath);
                    try
                    {
                        File.Move(newX86PluginPath, curX86PluginPath);
                        File.Move(newX86PluginPath + ".meta", curX86PluginPath + ".meta");

                        // fix the platform
                        string curX86PluginPathRel = "replacedets/Oculus/Spatializer/Plugins/x86/AudioPluginOculusSpatializer.dll";
                        UnityEngine.Debug.Log("path = " + curX86PluginPathRel);
                        replacedetDatabase.Importreplacedet(curX86PluginPathRel, ImportreplacedetOptions.ForceUpdate);
                        PluginImporter pi = PluginImporter.GetAtPath(curX86PluginPathRel) as PluginImporter;
                        pi.SetCompatibleWithEditor(false);
                        pi.SetCompatibleWithAnyPlatform(false);
                        pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
                        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false);
#if UNITY_2017_3_OR_NEWER
                        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);
#else
			            pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false);
			            pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false);
			            pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false);
#endif
                        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, true);
                        pi.SetCompatibleWithEditor(true);
                        pi.SetEditorData("CPU", "X86");
                        pi.SetEditorData("OS", "Windows");
                        pi.SetPlatformData("Editor", "CPU", "X86");
                        pi.SetPlatformData("Editor", "OS", "Windows");

                        replacedetDatabase.Importreplacedet(curX86PluginPathRel, ImportreplacedetOptions.ForceUpdate);
                        replacedetDatabase.Refresh();
                        replacedetDatabase.Savereplacedets();

                        upgradeDone = true;
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogWarning("Unable to rename the new spatializer plugin: " + e.Message);
                    }
                }
                string curX64PluginPath = Path.Combine(pluginsPath, "x86_64/AudioPluginOculusSpatializer.dll");
                if (File.Exists(newX64PluginPath))
                {
                    RenameSpatializerPluginToOld(curX64PluginPath);
                    try
                    {
                        File.Move(newX64PluginPath, curX64PluginPath);
                        File.Move(newX64PluginPath + ".meta", curX64PluginPath + ".meta");

                        // fix the platform
                        string curX64PluginPathRel = "replacedets/Oculus/Spatializer/Plugins/x86_64/AudioPluginOculusSpatializer.dll";
                        UnityEngine.Debug.Log("path = " + curX64PluginPathRel);
                        replacedetDatabase.Importreplacedet(curX64PluginPathRel, ImportreplacedetOptions.ForceUpdate);
                        PluginImporter pi = PluginImporter.GetAtPath(curX64PluginPathRel) as PluginImporter;
                        pi.SetCompatibleWithEditor(false);
                        pi.SetCompatibleWithAnyPlatform(false);
                        pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
                        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false);
#if UNITY_2017_3_OR_NEWER
                        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);
#else
		                pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false);
		                pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false);
		                pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false);
#endif
                        pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, true);
                        pi.SetCompatibleWithEditor(true);
                        pi.SetEditorData("CPU", "X86_64");
                        pi.SetEditorData("OS", "Windows");
                        pi.SetPlatformData("Editor", "CPU", "X86_64");
                        pi.SetPlatformData("Editor", "OS", "Windows");

                        replacedetDatabase.Importreplacedet(curX64PluginPathRel, ImportreplacedetOptions.ForceUpdate);
                        replacedetDatabase.Refresh();
                        replacedetDatabase.Savereplacedets();

                        upgradeDone = true;
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogWarning("Unable to rename the new spatializer plugin: " + e.Message);
                    }
                }
                
                if (upgradeDone)
                {
                    if (unityRunningInBatchmode
                        || EditorUtility.DisplayDialog("Restart Unity",
                            "Spatializer plugins has been upgraded."
                                + "\n\nPlease restart the Unity Editor to complete the update process."
#if !UNITY_2017_1_OR_NEWER
 + " You may need to manually relaunch Unity if you are using Unity 5.6 and higher."
#endif
,
                            "Restart",
                            "Not Now"))
                    {
                        RestartUnityEditor();
                    }
                }
            }
        }
    }

19 View Source File : ShellUpgradeTask.cs
License : MIT License
Project Creator : Accelerider

protected override async void OnDownloadCompleted(UpgradeInfo info)
        {
            base.OnDownloadCompleted(info);

            if (info.Version <= CurrentVersion) return;

            var launcherPath = Directory
                .GetFiles(GetInstallPath(info.Version))
                .SingleOrDefault(item => Path.GetFileName(item) == ProcessController.LauncherName);

            if (!string.IsNullOrEmpty(launcherPath))
            {
                try
                {
                    if (File.Exists(ProcessController.LauncherPath))
                    {
                        File.Delete(ProcessController.LauncherPath);
                    }
                    File.Move(launcherPath, ProcessController.LauncherPath);
                }
                catch (Exception e)
                {
                    Logger.Error($"[MOVE FILE] Move the {ProcessController.LauncherName} file failed. ", e);
                }
            }

            await ShowUpgradeNotificationDialogAsync(info);
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

public static void FileMove(this RetryPolicy retryPolicy, string sourceFileName, string destFileName)
		{
			retryPolicy.ExecuteAction(() => File.Move(sourceFileName, destFileName));
		}

19 View Source File : CustomPlatformEditor.cs
License : GNU General Public License v3.0
Project Creator : affederaffe

public override void OnInspectorGUI() 
        {
            DrawDefaultInspector();

            if (GUILayout.Button("Export")) 
            {
                string path = EditorUtility.SaveFilePanel("Save Platform file", "", customPlat.platName + ".plat", "plat");

                BuildTargetGroup selectedBuildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
                BuildTarget activeBuildTarget = EditorUserBuildSettings.activeBuildTarget;

                if (!string.IsNullOrEmpty(path)) 
                {
                    string fileName = Path.GetFileName(path);
                    string folderPath = Path.GetDirectoryName(path);

                    PrefabUtility.SaveAsPrefabreplacedet(customPlat.gameObject, "replacedets/_CustomPlatform.prefab");
                    replacedetBundleBuild replacedetBundleBuild = default;
                    replacedetBundleBuild.replacedetBundleName = fileName;
                    replacedetBundleBuild.replacedetNames = new string[] 
                    {
                        "replacedets/_CustomPlatform.prefab"
                    };

                    BuildPipeline.BuildreplacedetBundles(Application.temporaryCachePath, new replacedetBundleBuild[] { replacedetBundleBuild }, BuildreplacedetBundleOptions.ForceRebuildreplacedetBundle, EditorUserBuildSettings.activeBuildTarget);
                    EditorPrefs.SetString("currentBuildingreplacedetBundlePath", folderPath);
                    EditorUserBuildSettings.SwitchActiveBuildTarget(selectedBuildTargetGroup, activeBuildTarget);

                    replacedetDatabase.Deletereplacedet("replacedets/_CustomPlatform.prefab");

                    if (File.Exists(path))
                        File.Delete(path);

                    File.Move(Application.temporaryCachePath + "/" + fileName, path);

                    replacedetDatabase.Refresh();

                    EditorUtility.DisplayDialog("Exportation Successful!", "Exportation Successful!", "OK");
                }
                else 
                {
                    EditorUtility.DisplayDialog("Exportation Failed!", "Path is invalid.", "OK");
                }

            }
        }

19 View Source File : SaveOperation.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

protected override void DoOperation()
	{
		SaveAsOperation sao = new SaveAsOperation(byteBuffer, tempPath, this.progressCallback, null, false);
		stageReached = SaveStage.BeforeSaveAs;

		// Check for free space for final file
		// free space for temporary file is checked in sao.DoOperation()
		if (!CheckFreeSpace(Path.GetDirectoryName(byteBuffer.Filename), byteBuffer.fileBuf.Size)) {
			string msg = string.Format(Catalog.GetString("There is not enough free space on the device to save file '{0}'."), byteBuffer.Filename);
			throw new IOException(msg);
		}

		// Save ByteBuffer as a temp file
		sao.OperationThread();

		if (sao.Result == ThreadedAsyncOperation.OperationResult.CaughtException)
			throw sao.ThreadException;
		else if (sao.Result == ThreadedAsyncOperation.OperationResult.Cancelled)	
			cancelled = true;

		// if user hasn't cancelled, move temp file to 
		// its final location	
		if (!cancelled) {
			this.ActivateProgressReport(true);
			stageReached = SaveStage.BeforeDelete;
			
			// Delete here to fail early (before invalidating the byteBuffer)
			// if there are any issues.
			if (System.IO.File.Exists(savePath))
				System.IO.File.Delete(savePath);

			// close the file, make sure that File Operations
			// are temporarily allowed
			lock(byteBuffer.LockObj) {
				// CloseFile invalidates the file buffer,
				// so make sure undo/redo data stays valid
				byteBuffer.MakePrivateCopyOfUndoRedo();
				byteBuffer.FileOperationsAllowed = true;
				byteBuffer.CloseFile();
				byteBuffer.FileOperationsAllowed = false;
			}
			
			stageReached = SaveStage.BeforeMove;
			System.IO.File.Move(tempPath, savePath);
		}	
	}

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

public void Rebuild()
        {
            if (Header.EntryCount > 0)
            {
                string tempFilename = _filename + ".temp";
                var tempFS = new FileStream(tempFilename, FileMode.Create, FileAccess.Write);
                try
                {
                    var bw = new BinaryWriter(tempFS);

                    Header.Write(bw);

                    // Recalculate the offset/sizes of the TOC entries
                    var tocOffset = tempFS.Position;

                    var dataOffset = TOC.GetTOCBlockSize();

                    tempFS.Seek(dataOffset * TOCEntry.BlockSize, SeekOrigin.Begin);
                    foreach (var entry in TOC)
                    {
                        if (entry.CustomData == null)
                        {
                            bw.Write(ReadData(entry.OffsetBlock * TOCEntry.BlockSize, entry.UsedBlocks * TOCEntry.BlockSize));
                        }
                        else
                        {
                            var blockCount = (int) Math.Ceiling((float) entry.CustomData.Length/TOCEntry.BlockSize);
                            entry.UsedBlocks = (short)blockCount;
                            
                            bw.Write( entry.CustomData );
                            
                            if ( (entry.CustomData.Length % TOCEntry.BlockSize) != 0 )
                            {
                                var padding = new byte[ blockCount * TOCEntry.BlockSize - entry.CustomData.Length ];
                                bw.Write(padding);
                            }
                        }
                        entry.OffsetBlock = dataOffset;
                        dataOffset += entry.UsedBlocks;
                    }

                    tempFS.Seek(tocOffset, SeekOrigin.Begin);

                    TOC.Write( bw );

                }
                finally
                {
                    tempFS.Close();
                }

                Close();
                
                System.IO.File.Delete( _filename );
                System.IO.File.Move( tempFilename, _filename );

                Open(_filename);
            }
        }

19 View Source File : FileManagerOnDisk.cs
License : MIT License
Project Creator : ahmet-cetinkaya

public string Add(IFormFile file, string path)
        {
            var sourcepath = Path.GetTempFileName();

            if (file.Length > 0)
                using (var stream = new FileStream(sourcepath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

            File.Move(sourcepath, path);
            return path;
        }

19 View Source File : Main.cs
License : MIT License
Project Creator : AhmedMinegames

private void ObfuscasteCode(string ToProtect)
        {
            ModuleContext ModuleCont = ModuleDefMD.CreateModuleContext();
            ModuleDefMD FileModule = ModuleDefMD.Load(ToProtect, ModuleCont);
            replacedemblyDef replacedembly1 = FileModule.replacedembly;

            if (checkBox7.Checked)
            {
                foreach (var tDef in FileModule.Types)
                {
                    if (tDef == FileModule.GlobalType) continue;
                    foreach (var mDef in tDef.Methods)
                    {
                        if (mDef.Name.StartsWith("get_") || mDef.Name.StartsWith("set_")) continue;
                        if (!mDef.HasBody || mDef.IsConstructor) continue;
                        mDef.Body.SimplifyBranches();
                        mDef.Body.SimplifyMacros(mDef.Parameters);
                        var blocks = GetMethod(mDef);
                        var ret = new List<Block>();
                        foreach (var group in blocks)
                        {
                            Random rnd = new Random();
                            ret.Insert(rnd.Next(0, ret.Count), group);
                        }
                        blocks = ret;
                        mDef.Body.Instructions.Clear();
                        var local = new Local(mDef.Module.CorLibTypes.Int32);
                        mDef.Body.Variables.Add(local);
                        var target = Instruction.Create(OpCodes.Nop);
                        var instr = Instruction.Create(OpCodes.Br, target);
                        var instructions = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, 0) };
                        foreach (var instruction in instructions)
                            mDef.Body.Instructions.Add(instruction);
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc, local));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Br, instr));
                        mDef.Body.Instructions.Add(target);
                        foreach (var block in blocks.Where(block => block != blocks.Single(x => x.Number == blocks.Count - 1)))
                        {
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc, local));
                            var instructions1 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, block.Number) };
                            foreach (var instruction in instructions1)
                                mDef.Body.Instructions.Add(instruction);
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ceq));
                            var instruction4 = Instruction.Create(OpCodes.Nop);
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, instruction4));

                            foreach (var instruction in block.Instructions)
                                mDef.Body.Instructions.Add(instruction);

                            var instructions2 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, block.Number + 1) };
                            foreach (var instruction in instructions2)
                                mDef.Body.Instructions.Add(instruction);

                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc, local));
                            mDef.Body.Instructions.Add(instruction4);
                        }
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc, local));
                        var instructions3 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, blocks.Count - 1) };
                        foreach (var instruction in instructions3)
                            mDef.Body.Instructions.Add(instruction);
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ceq));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, instr));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Br, blocks.Single(x => x.Number == blocks.Count - 1).Instructions[0]));
                        mDef.Body.Instructions.Add(instr);

                        foreach (var lastBlock in blocks.Single(x => x.Number == blocks.Count - 1).Instructions)
                            mDef.Body.Instructions.Add(lastBlock);
                    }
                }
            }

            if (checkBox2.Checked)
            {
                for (int i = 200; i < 300; i++)
                {
                    InterfaceImpl Interface = new InterfaceImplUser(FileModule.GlobalType);
                    TypeDef typedef = new TypeDefUser("", $"Form{i.ToString()}", FileModule.CorLibTypes.GetTypeRef("System", "Attribute"));
                    InterfaceImpl interface1 = new InterfaceImplUser(typedef);
                    FileModule.Types.Add(typedef);
                    typedef.Interfaces.Add(interface1);
                    typedef.Interfaces.Add(Interface);
                }
            }

            string[] FakeObfuscastionsAttributes = { "ConfusedByAttribute", "YanoAttribute", "NetGuard", "DotfuscatorAttribute", "BabelAttribute", "ObfuscatedByGoliath", "dotNetProtector" };
            if (checkBox5.Checked)
            {
                for (int i = 0; i < FakeObfuscastionsAttributes.Length; i++)
                {
                    var FakeObfuscastionsAttribute = new TypeDefUser(FakeObfuscastionsAttributes[i], FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(FakeObfuscastionsAttribute);
                }
            }

            if (checkBox8.Checked)
            {
                foreach (TypeDef type in FileModule.Types)
                {
                    FileModule.Name = RandomName(12);
                    if (type.IsGlobalModuleType || type.IsRuntimeSpecialName || type.IsSpecialName || type.IsWindowsRuntime || type.IsInterface)
                    {
                        continue;
                    }
                    else
                    {
                        for (int i = 200; i < 300; i++)
                        {
                            foreach (PropertyDef property in type.Properties)
                            {
                                if (property.IsRuntimeSpecialName) continue;
                                property.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (FieldDef fields in type.Fields)
                            {
                                fields.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (EventDef eventdef in type.Events)
                            {
                                eventdef.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (MethodDef method in type.Methods)
                            {
                                if (method.IsConstructor || method.IsRuntimeSpecialName || method.IsRuntime || method.IsStaticConstructor || method.IsVirtual) continue;
                                method.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach(MethodDef method in type.Methods)
                            {
                                foreach(Parameter RenameParameters in method.Parameters)
                                {
                                    RenameParameters.Name = RandomName(10);
                                }
                            }
                        }
                    }
                    foreach (ModuleDefMD module in FileModule.replacedembly.Modules)
                    {
                        module.Name = RandomName(13);
                        module.replacedembly.Name = RandomName(14);
                    }
                }

                foreach (TypeDef type in FileModule.Types)
                {
                    foreach (MethodDef GetMethods in type.Methods)
                    {
                        for (int i = 200; i < 300; i++)
                        {
                            if (GetMethods.IsConstructor || GetMethods.IsRuntimeSpecialName || GetMethods.IsRuntime || GetMethods.IsStaticConstructor) continue;
                            GetMethods.Name = RandomName(15) + i;
                        }
                    }
                }
            }

            if (checkBox6.Checked)
            {
                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser(RandomName(10) + i + RandomName(10) + i + RandomName(10) + i, FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(Junk);
                }

                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser("<" + RandomName(10) + i + RandomName(10) + i + RandomName(10) + i + ">", FileModule.CorLibTypes.Object.TypeDefOrRef);
                    var Junk2 = new TypeDefUser(RandomName(11) + i + RandomName(11) + i + RandomName(11) + i, FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(Junk);
                    FileModule.Types.Add(Junk2);
                }

                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser("<" + RandomName(10) + i + RandomName(10) + i + RandomName(10) + i + ">", FileModule.CorLibTypes.Object.Namespace);
                    var Junk2 = new TypeDefUser(RandomName(11) + i + RandomName(11) + i + RandomName(11) + i, FileModule.CorLibTypes.Object.Namespace);
                    FileModule.Types.Add(Junk);
                    FileModule.Types.Add(Junk2);
                }
            }

            if (checkBox1.Checked)
            {
                foreach (TypeDef type in FileModule.Types)
                {
                    foreach (MethodDef method in type.Methods)
                    {
                        if (method.Body == null) continue;
                        method.Body.SimplifyBranches();
                        for (int i = 0; i < method.Body.Instructions.Count; i++)
                        {
                            if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                            {
                                string EncodedString = method.Body.Instructions[i].Operand.ToString();
                                string InsertEncodedString = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(EncodedString));
                                method.Body.Instructions[i].OpCode = OpCodes.Nop;
                                method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, FileModule.Import(typeof(Encoding).GetMethod("get_UTF8", new Type[] { }))));
                                method.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Ldstr, InsertEncodedString));
                                method.Body.Instructions.Insert(i + 3, new Instruction(OpCodes.Call, FileModule.Import(typeof(Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
                                method.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Callvirt, FileModule.Import(typeof(Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
                                i += 4;
                            }
                        }
                    }
                }
            }

            if (checkBox10.Checked)
            {
                foreach (var type in FileModule.GetTypes())
                {
                    if (type.IsGlobalModuleType) continue;
                    foreach (var method in type.Methods)
                    {
                        if (!method.HasBody) continue;
                        {
                            for (var i = 0; i < method.Body.Instructions.Count; i++)
                            {
                                if (!method.Body.Instructions[i].IsLdcI4()) continue;
                                var numorig = new Random(Guid.NewGuid().GetHashCode()).Next();
                                var div = new Random(Guid.NewGuid().GetHashCode()).Next();
                                var num = numorig ^ div;
                                var nop = OpCodes.Nop.ToInstruction();
                                var local = new Local(method.Module.ImportAsTypeSig(typeof(int)));
                                method.Body.Variables.Add(local);
                                method.Body.Instructions.Insert(i + 1, OpCodes.Stloc.ToInstruction(local));
                                method.Body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Ldc_I4, method.Body.Instructions[i].GetLdcI4Value() - sizeof(float)));
                                method.Body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Ldc_I4, num));
                                method.Body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Ldc_I4, div));
                                method.Body.Instructions.Insert(i + 5, Instruction.Create(OpCodes.Xor));
                                method.Body.Instructions.Insert(i + 6, Instruction.Create(OpCodes.Ldc_I4, numorig));
                                method.Body.Instructions.Insert(i + 7, Instruction.Create(OpCodes.Bne_Un, nop));
                                method.Body.Instructions.Insert(i + 8, Instruction.Create(OpCodes.Ldc_I4, 2));
                                method.Body.Instructions.Insert(i + 9, OpCodes.Stloc.ToInstruction(local));
                                method.Body.Instructions.Insert(i + 10, Instruction.Create(OpCodes.Sizeof, method.Module.Import(typeof(float))));
                                method.Body.Instructions.Insert(i + 11, Instruction.Create(OpCodes.Add));
                                method.Body.Instructions.Insert(i + 12, nop);
                                i += 12;
                            }
                            method.Body.SimplifyBranches();
                        }
                    }
                }
            }

            if (checkBox11.Checked)
            {
                foreach (ModuleDef module in FileModule.replacedembly.Modules)
                {
                    TypeRef attrRef = FileModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressIldasmAttribute");
                    var ctorRef = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef);
                    var attr = new CustomAttribute(ctorRef);
                    module.CustomAttributes.Add(attr);
                }
            }

            if (checkBox13.Checked)
            {
                // later
            }

            if (File.Exists(Environment.CurrentDirectory + @"\Obfuscasted.exe") == false)
            {
                File.Copy(ToProtect, Environment.CurrentDirectory + @"\Obfuscasted.exe");
                FileModule.Write(Environment.CurrentDirectory + @"\Obfuscasted.exe");
                if (checkBox12.Checked)
                {
                    string RandomreplacedemblyName = RandomName(12);
                    PackAndEncrypt(Environment.CurrentDirectory + @"\Obfuscasted.exe", Environment.CurrentDirectory + @"\" + RandomreplacedemblyName + ".tmp");
                    File.Delete(Environment.CurrentDirectory + @"\Obfuscasted.exe");
                    File.Move(Environment.CurrentDirectory + @"\" + RandomreplacedemblyName + ".tmp", Environment.CurrentDirectory + @"\Obfuscasted.exe");
                }
            }
            else
            {
                MessageBox.Show("Please Delete or move the file: " + Environment.CurrentDirectory + @"\Obfuscasted.exe" + " first to Obfuscaste your file", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
        }

19 View Source File : FileSystemStore.cs
License : MIT License
Project Creator : aishang2015

public Task MoveFileAsync(string oldPath, string newPath)
        {
            var physicalOldPath = GetPhysicalPath(oldPath);

            if (!File.Exists(physicalOldPath))
            {
                throw new FileStoreException($"Cannot move file '{oldPath}' because it does not exist.");
            }

            var physicalNewPath = GetPhysicalPath(newPath);

            if (File.Exists(physicalNewPath) || Directory.Exists(physicalNewPath))
            {
                throw new FileStoreException($"Cannot move file because the new path '{newPath}' already exists.");
            }

            File.Move(physicalOldPath, physicalNewPath);

            return Task.CompletedTask;
        }

19 View Source File : DiskAccess.cs
License : MIT License
Project Creator : AiursoftWeb

public void DeleteToTrash(string hardwareUuid)
        {
            var path = _path + $"{hardwareUuid}.dat";
            var target = _trashPath + $"{hardwareUuid}.dat";
            if (File.Exists(path))
            {
                if (!Directory.Exists(_trashPath))
                {
                    Directory.CreateDirectory(_trashPath);
                }
                File.Move(path, target);
            }
        }

19 View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6

private bool buildBase()
        {
            this.outputText.Visible = true;

            if (!File.Exists(Path.Combine(nxDir, "baserom.us.z64")))
            {
                if (File.Exists(Path.Combine(nxDir, "baserom.us.z64")))
                {
                    File.Move(Path.Combine(nxDir, "baserom.us.z64"), Path.Combine(nxDir, "baserom.us.z64"));
                }
                else
                {
                    MessageBox.Show("You are missing baserom.us.z64.\n\nPlease select your baserom.us.z64.", "ROM Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Boolean exit = false;
                    var result = new OpenFileDialog();
                    while (!exit)
                    {
                        if (result.ShowDialog() == DialogResult.OK)
                        {
                            if (checkHash(result.FileName))
                            {
                                File.Copy(result.FileName, Path.Combine(nxDir, "baserom.us.z64"));
                                exit = true;
                            }
                            else
                            {
                                var answer = MessageBox.Show("ROM hash is not valid.\n\nWould you like to select another?", "Invalid ROM Hash", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                                if (answer == DialogResult.No) return true;
                            }
                        }
                        else
                        {
                            return true;
                        }
                    }
                }
            }
            if (runProcess("cmd.exe", @"/C build.bat"))
            {
                this.outputText.Text += "Traditional build.bat file failed.\n\nAttempting static calls as a fallback...\n\n";

                if (runProcess("cmd.exe", " /C py extract_replacedets.py && py ..\\scripts\\pak.py --source . --output ..\\romfs\\!!base.pak"))
                {
                    MessageBox.Show("!!Base.pak failed to build.\n\nCheck for error messages in log or share them with troubleshooters.", "Base PAK Build Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return true;
                }
            }
            
            return false;
        }

19 View Source File : FileBackup.cs
License : MIT License
Project Creator : AkiniKites

public static bool RunWithBackup(string path, Func<bool> action)
        {
            var success = false;

            try
            {
                if (File.Exists(path) && action())
                    success = true;
            }
            catch (Exception ex)
            {
                Errors.WriteError(ex);
            }

            var backupFiles = GetMatchingFiles(path).ToList();

            if (!success && backupFiles.Any())
            {
                if (File.Exists(path)) File.Delete(path);
                File.Move(backupFiles.First(), path);
                success = action();
            }

            foreach (var file in backupFiles)
            {
                if (File.Exists(file)) File.Delete(file);
            }

            return success;
        }

19 View Source File : FileBackup.cs
License : MIT License
Project Creator : AkiniKites

public void Dispose()
        {
            if (_tempPath != null && File.Exists(_tempPath))
            {
                if (File.Exists(_path)) File.Delete(_path);
                File.Move(_tempPath, _path);
            }
        }

19 View Source File : ContentsBrowser.cs
License : MIT License
Project Creator : alaabenfatma

private void ApplyNewName()
        {
            _tag.Visibility = Visibility.Visible;
            _renameBox.Visibility = Visibility.Collapsed;
            var oldPAth = Path;
            var newPath = Parent.Path + @"\" + _renameBox.Text;
            MagicLaboratory.CleanPath(ref newPath);
            try
            {
                if (!Folder)
                    if (File.Exists(Path))
                    {
                        File.Move(Path
                            , newPath);
                        ItemName = _renameBox.Text;
                        var itemName = ItemName;
                        MagicLaboratory.CleanPath(ref itemName);
                        ItemName = itemName;
                        Path = newPath;
                    }

                if (Directory.Exists(Path) && Path != newPath)
                {
                    Directory.Move(Path
                        , Uri.UnescapeDataString(newPath));
                    ItemName = _renameBox.Text;
                    var itemName = ItemName;
                    MagicLaboratory.CleanPath(ref itemName);
                    ItemName = itemName;
                    Path = newPath;
                    var node = Parent.Container.GetNode(oldPAth, Parent.Container.FoldersTree.Items);
                    var parentNode = Parent.Container.GetNode(Parent.Path, Parent.Container.FoldersTree.Items);
                    if (node == null)
                    {
                        parentNode.Items.Add(new TreeViewItem {Header = new FolderItem(Path, ItemName)});
                    }
                    else
                    {
                        var folderItem = node.Header as FolderItem;
                        if (folderItem != null)
                        {
                            folderItem.FolderName = itemName;
                            folderItem.Path = Path;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var result = MessageBox.Show(ex.Message + "\n" + "Try again?", "Couldn't modify the name.",
                    MessageBoxButton.YesNo, MessageBoxImage.Error);
                Parent.Container.Disable();
                if (result == MessageBoxResult.Yes)
                {
                    Parent.Container.Enable();
                    Rename();
                }
            }
        }

19 View Source File : AesBase.cs
License : MIT License
Project Creator : alecgn

internal AesEncryptionResult EncryptWithFileStream(string sourceFilePath, string encryptedFilePath, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC,
            PaddingMode paddingMode = PaddingMode.PKCS7, bool deleteSourceFile = false, int kBbufferSize = 4)
        {
            if (!File.Exists(sourceFilePath))
            {
                return new AesEncryptionResult()
                {
                    Success = false,
                    //Message = $"{MessageStrings.Common_FileNotFound} \"{sourceFilePath}\"."
                    Message = $"{MessageStrings.Common_FileNotFound} \"{sourceFilePath}\"."
                };
            }

            if (string.IsNullOrWhiteSpace(encryptedFilePath))
            {
                return new AesEncryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Encryption_EncryptedFilePathError
                };
            }

            var destinationDirectory = Path.GetDirectoryName(encryptedFilePath);

            if (!Directory.Exists(destinationDirectory))
            {
                return new AesEncryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_DestinationDirectoryNotFound} \"{destinationDirectory}\"."
                };
            }

            _key = key ?? _key;
            _IV = IV ?? _IV;

            var pathsEqual = encryptedFilePath.Equals(sourceFilePath, StringComparison.InvariantCultureIgnoreCase);

            try
            {
                using (var aesManaged = new AesManaged())
                {
                    if (_key == null)
                    {
                        aesManaged.GenerateKey();
                        _key = aesManaged.Key;
                    }
                    else
                    {
                        if (aesManaged.ValidKeySize((_key.Length * 8)))
                        {
                            aesManaged.Key = _key;
                        }
                        else
                        {
                            return new AesEncryptionResult()
                            {
                                Success = false,
                                Message = $"{MessageStrings.Common_InvalidKeySizeError} ({(_key.Length * 8)})."
                            };
                        }
                    }

                    if (_IV == null || _IV.Length == 0)
                    {
                        aesManaged.GenerateIV();
                        _IV = aesManaged.IV;
                    }
                    else
                    {
                        aesManaged.IV = _IV;
                    }

                    aesManaged.Mode = cipherMode;
                    aesManaged.Padding = paddingMode;

                    using (var encryptor = aesManaged.CreateEncryptor(_key, _IV))
                    {
                        using (var sourceFs = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            using (var encryptedFs = File.Open((pathsEqual ? encryptedFilePath + "_tmpcrypt" : encryptedFilePath), FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                using (var cs = new CryptoStream(encryptedFs, encryptor, CryptoStreamMode.Write))
                                {
                                    //plain.CopyTo(cs);

                                    var buffer = new byte[kBbufferSize * 1024];
                                    int read;
                                    var percentageDone = 0;

                                    while ((read = sourceFs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        cs.Write(buffer, 0, read);

                                        var tmpPercentageDone = (int)(sourceFs.Position * 100 / sourceFs.Length);

                                        if (tmpPercentageDone != percentageDone)
                                        {
                                            percentageDone = tmpPercentageDone;

                                            RaiseOnEncryptionProgress(percentageDone, (percentageDone != 100 ? $"Encrypting ({percentageDone}%)..." : $"Encrypted ({percentageDone}%)."));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(sourceFilePath);
                    File.Move(encryptedFilePath + "_tmpcrypt", encryptedFilePath);
                }

                if (deleteSourceFile && !pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(sourceFilePath);
                }

                //var message = $"File \"{sourceFilePath}\" successfully encrypted to \"{encryptedFilePath}\".";
                var message = string.Format(MessageStrings.Encryption_FileEncryptSuccess, sourceFilePath, encryptedFilePath);
                message += (deleteSourceFile && !pathsEqual ? $"\n{string.Format(MessageStrings.Encryption_FileDeleted, sourceFilePath)}" : "");

                return new AesEncryptionResult()
                {
                    Success = true,
                    Message = message,
                    Key = _key,
                    IV = _IV,
                    AesCipherMode = (AesCipherMode)cipherMode,
                    PaddingMode = paddingMode
                };
            }
            catch (Exception ex)
            {
                return new AesEncryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_ExceptionError}\n{ex.ToString()}"
                };
            }
        }

19 View Source File : AesBase.cs
License : MIT License
Project Creator : alecgn

internal AesDecryptionResult DecryptWithFileStream(string encryptedFilePath, string decryptedFilePath, byte[] key, byte[] IV, CipherMode cipherMode = CipherMode.CBC,
            PaddingMode paddingMode = PaddingMode.PKCS7, bool deleteEncryptedFile = false, int kBbufferSize = 4, long startPosition = 0, long endPosition = 0)
        {
            if (!File.Exists(encryptedFilePath))
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Decryption_EncryptedFileNotFound} \"{encryptedFilePath}\"."
                };
            }

            if (string.IsNullOrWhiteSpace(decryptedFilePath))
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_DecryptedFilePathError
                };
            }

            var destinationDirectory = Path.GetDirectoryName(decryptedFilePath);

            if (!Directory.Exists(destinationDirectory))
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_DestinationDirectoryNotFound} \"{destinationDirectory}\"."
                };
            }

            _key = key ?? _key;
            _IV = IV ?? _IV;

            if (_key == null)
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_NullKeyError
                };
            }

            if (_IV == null)
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_NullIVError
                };
            }

            if (endPosition < startPosition)
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = string.Format(MessageStrings.Decryption_EndPositionLessThanStartError, endPosition, startPosition)
                };
            }

            var pathsEqual = decryptedFilePath.Equals(encryptedFilePath, StringComparison.InvariantCultureIgnoreCase);

            try
            {
                using (var aesManaged = new AesManaged())
                {
                    aesManaged.Key = _key;
                    aesManaged.IV = _IV;
                    aesManaged.Mode = cipherMode;
                    aesManaged.Padding = paddingMode;

                    using (var decryptedFs = File.Open((pathsEqual ? decryptedFilePath + "_tmpdecrypt" : decryptedFilePath), FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        using (var encryptedFs = File.Open(encryptedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            encryptedFs.Position = startPosition;

                            using (var decryptor = aesManaged.CreateDecryptor(_key, _IV))
                            {
                                using (var cs = new CryptoStream(decryptedFs, decryptor, CryptoStreamMode.Write))
                                {
                                    //encrypted.CopyTo(cs);

                                    var buffer = new byte[kBbufferSize * 1024];
                                    var totalBytesToRead = ((endPosition == 0 ? encryptedFs.Length : endPosition) - startPosition);
                                    var totalBytesNotRead = totalBytesToRead;
                                    long totalBytesRead = 0;
                                    var percentageDone = 0;

                                    while (totalBytesNotRead > 0)
                                    {
                                        var bytesRead = encryptedFs.Read(buffer, 0, (int)Math.Min(buffer.Length, totalBytesNotRead));

                                        if (bytesRead > 0)
                                        {
                                            cs.Write(buffer, 0, bytesRead);

                                            totalBytesRead += bytesRead;
                                            totalBytesNotRead -= bytesRead;
                                            var tmpPercentageDone = (int)(totalBytesRead * 100 / totalBytesToRead);

                                            if (tmpPercentageDone != percentageDone)
                                            {
                                                percentageDone = tmpPercentageDone;

                                                RaiseOnDecryptionProgress(percentageDone, (percentageDone != 100 ? $"Decrypting ({percentageDone}%)..." : $"Decrypted ({percentageDone}%)."));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(encryptedFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(encryptedFilePath);
                    File.Move(decryptedFilePath + "_tmpdecrypt", decryptedFilePath);
                }

                if (deleteEncryptedFile && !pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(encryptedFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(encryptedFilePath);
                }

                var message = string.Format(MessageStrings.Decryption_FileDecryptSuccess, encryptedFilePath, decryptedFilePath);
                message += (deleteEncryptedFile && !pathsEqual ? $"\n{string.Format(MessageStrings.Encryption_FileDeleted, encryptedFilePath)}" : "");

                return new AesDecryptionResult()
                {
                    Success = true,
                    Message = message,
                    Key = _key,
                    IV = _IV,
                    AesCipherMode = (AesCipherMode)cipherMode,
                    PaddingMode = paddingMode
                };
            }
            catch (Exception ex)
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Decryption_ExceptionError}\n{ex.ToString()}"
                };
            }
        }

19 View Source File : DoCreatePWNodeScript.cs
License : MIT License
Project Creator : alelievr

public override void Action(int instanceId, string pathName, string resourceFile)
		{
			string name = Path.GetFileNameWithoutExtension(pathName);

			if (!File.Exists(nodeTemplate))
				TryFindEditorPath();
			
			//Node editor file replacedet
			createScriptreplacedet.Invoke(null, new object[]{ pathName, nodeEditorTemplate });
			File.Move(Path.GetFullPath(pathName), Application.dataPath + ProceduralWorldsEditorPath + "/" + name + "Editor.cs");
			
			//then node file replacedet
			createScriptreplacedet.Invoke(null, new object[]{ pathName, nodeTemplate });

			var replacedet = replacedetDatabase.LoadreplacedetAtPath(pathName, typeof(MonoScript));
			ProjectWindowUtil.ShowCreatedreplacedet(replacedet);

			replacedetDatabase.Refresh();
		}

19 View Source File : PersistentSettings.cs
License : MIT License
Project Creator : AlexGyver

public void Save(string fileName) {

      XmlDoreplacedent doc = new XmlDoreplacedent();
      doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
      XmlElement configuration = doc.CreateElement("configuration");
      doc.AppendChild(configuration);
      XmlElement appSettings = doc.CreateElement("appSettings");
      configuration.AppendChild(appSettings);
      foreach (KeyValuePair<string, string> keyValuePair in settings) {
        XmlElement add = doc.CreateElement("add");
        add.SetAttribute("key", keyValuePair.Key);
        add.SetAttribute("value", keyValuePair.Value);
        appSettings.AppendChild(add);
      }

      byte[] file;
      using (var memory = new MemoryStream()) {
        using (var writer = new StreamWriter(memory, Encoding.UTF8)) {
          doc.Save(writer);
        }
        file = memory.ToArray();
      }

      string backupFileName = fileName + ".backup";
      if (File.Exists(fileName)) {
        try {
          File.Delete(backupFileName);
        } catch { }
        try {
          File.Move(fileName, backupFileName);
        } catch { }
      }

      using (var stream = new FileStream(fileName, 
        FileMode.Create, FileAccess.Write))
      {
        stream.Write(file, 0, file.Length);
      }

      try {
        File.Delete(backupFileName);
      } catch { }
    }

19 View Source File : Rename.cs
License : MIT License
Project Creator : Alkl58

public static void RenameChunks(string currentPath)
        {
            //Create Array List with all Chunks
            string[] chunks;
            //Sets the Chunks directory
            string sdira = currentPath + "\\Chunks";
            //Add all Files in Chunks Folder to array
            chunks = Directory.GetFiles(sdira, "*mkv", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();
            DirectoryInfo d = new DirectoryInfo(currentPath + "\\Chunks");
            FileInfo[] infos = d.GetFiles();

            int numberOfChunks = chunks.Count();

            //outx.mkv = 8 | outxx.mkv = 9 (99) | outxxx.mkv = 10 (999) | outxxxx.mkv = 11 (9999) | outxxxxx.mkv = 12 (99999)

            //int numberOfChunks = 20000;

            if (numberOfChunks >= 10 && numberOfChunks <= 99)
            {
                foreach (FileInfo f in infos)
                {
                    int count = f.ToString().Count();

                    if (count == 8)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
                    }
                }
            }
            else if (numberOfChunks >= 100 && numberOfChunks <= 999) //If you have more than 100 Chunks and less than 999
            {
                foreach (FileInfo f in infos)
                {
                    int count = f.ToString().Count();

                    if (count == 8)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00"));
                    }

                    if (count == 9)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
                    }
                }
            }
            else if (numberOfChunks >= 1000 && numberOfChunks <= 9999) //If you have more than 1.000 Chunks and less than 9.999
            {
                foreach (FileInfo f in infos)
                {
                    int count = f.ToString().Count();

                    if (count == 8)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out000"));
                    }

                    if (count == 9)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00"));
                    }

                    if (count == 10)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
                    }
                }
            }
            else if (numberOfChunks >= 10000 && numberOfChunks <= 99999) //If you have more than 10.000 Chunks and less than 99.999
            {
                foreach (FileInfo f in infos)
                {
                    int count = f.ToString().Count();

                    if (count == 8)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0000"));
                    }

                    if (count == 9)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out000"));
                    }

                    if (count == 10)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00"));
                    }

                    if (count == 11)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
                    }
                }
            }
            else if (numberOfChunks >= 100000 && numberOfChunks <= 999999)
            {
                foreach (FileInfo f in infos)
                {
                    int count = f.ToString().Count();
                    //If you have more than 100.000 Chunks and less than 999.999
                    //BTW are fu*** insane?
                    if (count == 8)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00000"));
                    }

                    if (count == 9)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0000"));
                    }

                    if (count == 10)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out000"));
                    }

                    if (count == 11)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00"));
                    }
                    if (count == 12)
                    {
                        File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
                    }
                }
            }
        }

19 View Source File : Updater.xaml.cs
License : MIT License
Project Creator : Alkl58

private async void ButtonUpdateFFmpeg_Click(object sender, RoutedEventArgs e)
        {
            ToggleAllButtons(false);

            // Creates the ffmpeg folder if not existent
            if (!Directory.Exists(Path.Combine(CurrentDir, "Apps", "ffmpeg")))
            {
                Directory.CreateDirectory(Path.Combine(CurrentDir, "Apps", "ffmpeg"));
            }

            // Downloads ffmpeg
            await Task.Run(() => DownloadBin("https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z", Path.Combine(CurrentDir, "Apps", "ffmpeg-git-full.7z")));

            if (File.Exists(Path.Combine(CurrentDir, "Apps", "ffmpeg-git-full.7z")))
            {
                // Extracts ffmpeg
                ExtractFile(Path.Combine(CurrentDir, "Apps", "ffmpeg-git-full.7z"), Path.Combine(Directory.GetCurrentDirectory(), "Apps", "ffmpeg"));

                if (File.Exists(Path.Combine(CurrentDir, "Apps", "ffmpeg", Git_FFmpeg_Name, "bin", "ffmpeg.exe")))
                {
                    if (File.Exists(Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.exe")))
                    {
                        File.Delete(Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.txt"));
                        File.Delete(Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.exe"));
                    }

                    File.Move(Path.Combine(CurrentDir, "Apps", "ffmpeg", Git_FFmpeg_Name, "bin", "ffmpeg.exe"), Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.exe"));

                    File.WriteAllText(Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.txt"), FFmpegUpdateVersion);

                    File.Delete(Path.Combine(CurrentDir, "Apps", "ffmpeg-git-full.7z"));
                    Directory.Delete(Path.Combine(CurrentDir, "Apps", "ffmpeg", Git_FFmpeg_Name), true);

                    CompareLocalVersion();
                }
            }

            ToggleAllButtons(true);

            LabelProgressBar.Dispatcher.Invoke(() => LabelProgressBar.Content = "Finished updating FFmpeg");
        }

19 View Source File : Library.cs
License : MIT License
Project Creator : allisterb

public virtual bool CleanAndFixup()
        {
            if (File.Exists(Path.Combine(OutputDirName, Module.OutputNamespace + "-symbols.cpp")))
            {
                File.Delete(Path.Combine(OutputDirName, Module.OutputNamespace + "-symbols.cpp"));
                Info($"Removing unneeded file {Path.Combine(OutputDirName, Module.OutputNamespace + "-symbols.cpp")}");
            }
            if (File.Exists(Path.Combine(OutputDirName, "Std.cs")))
            {
                File.Delete(Path.Combine(OutputDirName, "Std.cs"));
                Info($"Removing unneeded file {Path.Combine(OutputDirName, "Std.cs")}");
            }
            if (!string.IsNullOrEmpty(OutputFileName))
            {
                string f = Path.Combine(Path.GetFullPath(OutputDirName), OutputFileName);
                if (!string.IsNullOrEmpty(OutputFileName) && F != f)
                {
                    if (Environment.OSVersion.Platform == PlatformID.Win32NT && F.ToLowerInvariant() == f.ToLowerInvariant())
                    {

                    }
                    else if (File.Exists(f))
                    {
                        Warn($"Overwriting file {f}.");
                        File.Delete(f);
                    }
                    File.Move(F, f);
                    F = f;
                }
            }
            if (!string.IsNullOrEmpty(Clreplaced))
            {
                string s = File.ReadAllText(F);
                s = Regex.Replace(s, $"public unsafe partial clreplaced {ModuleName}\\r?$", "public unsafe partial clreplaced " + Clreplaced, RegexOptions.Multiline);
                File.WriteAllText(F, s);
            }
            return true;
        }

19 View Source File : FileLogger.cs
License : GNU General Public License v3.0
Project Creator : Alois-xx

internal void RollOver()
        {
            string fileName = myFile.Name;
            myLog.Close();
            string dir = Path.GetDirectoryName(fileName);
            string ext = Path.GetExtension(fileName);
            string basename = Path.GetFileNameWithoutExtension(fileName);
            string newFileName = Path.Combine(dir, $"{basename}_{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff")}{ext}");
            File.Move(fileName, newFileName);
            string[] files = Directory.GetFiles(myLoggingDirectory, $"{Path.GetFileNameWithoutExtension(myFileBaseName)}*{Path.GetExtension(myFileBaseName)}");
            string [] sortedByAgeDescending = files.Select(f => new FileInfo(f)).OrderByDescending(x => x.LastWriteTime).Select(x => x.FullName).ToArray();
            
            for(int i=myMaxGenerationsToKeep;i<sortedByAgeDescending.Length;i++)
            {
                try
                {
                    Delete(sortedByAgeDescending[i]);
                }
                catch(Exception)
                {

                }
            }

            ReopenFileAndWriteHeader();
        }

19 View Source File : LauncherUpdater.cs
License : GNU General Public License v3.0
Project Creator : AM2R-Community-Developers

public static void Main()
        {
            log.Info("Running update check...");

            string version = VERSION.Replace(".", "");

            //update section

            //delete old files that have been left
            if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak"))
            {
                log.Info("AM2RLauncher.bak detected. Removing file.");
                File.Delete(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
            }
            if (currentPlatform.IsWinForms && File.Exists(oldConfigPath))
            {
                log.Info(CrossPlatformOperations.LAUNCHERNAME + ".oldCfg detected. Removing file.");
                File.Delete(oldConfigPath);
            }
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/oldLib"))
            {
                log.Info("Old lib folder detected, removing folder.");
                Directory.Delete(CrossPlatformOperations.CURRENTPATH + "/oldLib", true);
            }

            // Clean up old update libs
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
            {
                foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                {
                    if (file.Name.EndsWith(".bak"))
                        file.Delete();
                }

                // Do the same for each subdir
                foreach (DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                {
                    foreach (FileInfo file in dir.GetFiles())
                    {
                        if (file.Name.EndsWith(".bak"))
                            file.Delete();
                    }
                }
            }

            //check settings if autoUpdateLauncher is set to true
            bool autoUpdate = bool.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher"));

            if (autoUpdate)
            {
                log.Info("AutoUpdate Launcher set to true!");

                //this is supposed to fix the updater throwing an exception on windows 7 and earlier(?)
                //see this for information: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel and https://stackoverflow.com/a/50977774
                if (currentPlatform.IsWinForms)
                {
                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest");
                HttpWebResponse response = null;
                try
                {        
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException)
                {
                    log.Error("WebException caught! Displaying MessageBox.");
                    MessageBox.Show(Language.Text.NoInternetConnection);
                    return;
                }

                Uri realUri = response.ResponseUri;
                string onlineVersion = realUri.AbsoluteUri.Substring(realUri.AbsoluteUri.LastIndexOf('/') + 1);
                bool isCurrentVersionOutdated = false;

                string[] localVersionArray = VERSION.Split('.');
                string[] onlineVersionArray = onlineVersion.Split('.');

                for (int i = 0; i < localVersionArray.Length; i++)
                {
                    if (int.Parse(onlineVersionArray[i]) > int.Parse(localVersionArray[i]))
                    {
                        isCurrentVersionOutdated = true;
                        break;
                    }
                }

                if (isCurrentVersionOutdated)
                {
                    log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + ".");

                    string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/";
                    string zipPath = CrossPlatformOperations.CURRENTPATH + "/launcher.zip";

                    // Clean tmpupdate
                    if (Directory.Exists(tmpUpdatePath))
                        Directory.Delete(tmpUpdatePath);
                    if (!Directory.Exists(tmpUpdatePath))
                        Directory.CreateDirectory(tmpUpdatePath);

                    try
                    { 
                        using (var client = new WebClient())
                        {
                            string platformSuffix = "";
                            if (currentPlatform.IsWinForms) platformSuffix = "_win";
                            else if (currentPlatform.IsGtk) platformSuffix = "_lin";

                            log.Info("Downloading https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip to " + zipPath + ".");
                            
                            client.DownloadFile("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip", zipPath);

                            log.Info("File successfully downloaded.");
                        }
                    }
                    catch(UnauthorizedAccessException)
                    {
                        log.Error("UnauthorizedAccessException caught! Displaying MessageBox.");
                        MessageBox.Show(Language.Text.UnauthorizedAccessMessage);
                        return;
                    }

                    ZipFile.ExtractToDirectory(zipPath, tmpUpdatePath);
                    log.Info("Updates successfully extracted to " + tmpUpdatePath);

                    File.Delete(zipPath);
                    File.Move(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME, CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
                    if (currentPlatform.IsWinForms) File.Move(CrossPlatformOperations.LAUNCHERNAME + ".config", CrossPlatformOperations.LAUNCHERNAME + ".oldCfg");

                    foreach (var file in new DirectoryInfo(tmpUpdatePath).GetFiles())
                    {
                        log.Info("Moving " +  file.FullName + " to " + CrossPlatformOperations.CURRENTPATH + "/" + file.Name);
                        File.Copy(file.FullName, updatePath + "/" + file.Name, true);
                    }
                    // for windows, the actual application is in "AM2RLauncher.dll". Which means, we need to update the lib folder as well.
                    if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
                    {
                        // Directory.Move(CrossPlatformOperations.CURRENTPATH + "/lib", CrossPlatformOperations.CURRENTPATH + "/oldLib");
                        // So, because Windows behavior is dumb...

                        // Rename all files in lib to *.bak
                        foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                        {
                            file.CopyTo(file.Directory + file.Name + ".bak");
                        }

                        // Do the same for each subdir
                        foreach(DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                        {
                            foreach (FileInfo file in dir.GetFiles())
                            {
                                file.CopyTo(file.Directory + file.Name + ".bak");
                            }
                        }

                        // Yes, the above calls could be recursive. No, I can't be bothered to make them as such.

                        HelperMethods.DirectoryCopy(tmpUpdatePath + "lib", CrossPlatformOperations.CURRENTPATH + "/lib", true);
                    }
                    
                    Directory.Delete(tmpUpdatePath, true);

                    CrossPlatformOperations.CopyOldConfigToNewConfig();

                    log.Info("Files extracted. Preparing to restart executable...");

                    if (currentPlatform.IsGtk) System.Diagnostics.Process.Start("chmod", "+x ./AM2RLauncher.Gtk");

                    System.Diagnostics.Process.Start(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME);
                    Environment.Exit(0);
                }
            }
            else
            {
                log.Info("AutoUpdate Launcher set to false. Exiting update check.");
            }
        }

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

private static bool TestFileFree(string FileName)
        {
            try
            {
                File.Move(FileName, FileName);
                return true;
            }
            catch
            {
                return false;
            }
        }

19 View Source File : HelperMethods.cs
License : GNU General Public License v3.0
Project Creator : AM2R-Community-Developers

public static void RecursiveRollover(string logFile, int max = 9)
        {
            int index = 1;
            char endChar = logFile[logFile.Length - 1];
            string fileName;

            // If not the original file, set the new index and get the new fileName.
            if (char.IsNumber(endChar))
            {
                index = int.Parse(endChar.ToString()) + 1;
                fileName = logFile.Remove(logFile.Length - 1) + index;
            }
            else // Otherwise, if the original file, just set fileName to log.txt.1.
                fileName = logFile + ".1";

            // If new name already exists, run the rollover algorithm on it!
            if (File.Exists(fileName))
            {
                RecursiveRollover(fileName, max);
            }

            // If index is less than max, rename file.
            if (index < max)
            {
                File.Move(logFile, fileName);
            }
            else // Otherwise, delete the file.
                File.Delete(logFile);
        }

public static void ApplyXdeltaPatch(string original, string patch, string output)
        {
            // for *whatever reason* **sometimes** xdelta patching doesn't work, if output = original. So I'm fixing that here.
            string originalOutput = output;
            if (original == output)
                output = output += "_";

            string arguments = "-f -d -s \"" + original.Replace(CURRENTPATH + "/","") + "\" \"" + patch.Replace(CURRENTPATH + "/", "") + "\" \"" + output.Replace(CURRENTPATH + "/", "") + "\"";

            if (currentPlatform.IsWinForms)
            {
                // We want some fancy parameters for Windows because the terminal scares end users :(
                ProcessStartInfo parameters = new ProcessStartInfo
                {
                    FileName = CURRENTPATH + "/PatchData/utilities/xdelta/xdelta3.exe",
                    WorkingDirectory = CURRENTPATH + "",
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    Arguments = arguments
                };

                using (Process proc = new Process { StartInfo = parameters })
                {
                    proc.Start();

                    proc.WaitForExit();
                }
            }
            else if (currentPlatform.IsGtk)
            {
                ProcessStartInfo parameters = new ProcessStartInfo
                {
                    FileName = "xdelta3",
                    Arguments = arguments,
                    WorkingDirectory = CURRENTPATH
                };

                using (Process proc = Process.Start(parameters))
                {
                    proc.WaitForExit();
                }
            }

            if (originalOutput != output && File.Exists(output))
            {
                File.Delete(originalOutput);
                File.Move(output, originalOutput);
            }
        }

19 View Source File : ModPacker.cs
License : GNU General Public License v3.0
Project Creator : AM2R-Community-Developers

private void CreateModPack(string operatingSystem, string input, string output)
        {
            LoadProfileParameters(operatingSystem);

            // Cleanup in case of previous errors
            if (Directory.Exists(Path.GetTempPath() + "\\AM2RModPacker"))
            {
                Directory.Delete(Path.GetTempPath() + "\\AM2RModPacker", true);
            }

            // Create temp work folders
            string tempPath = "",
                   tempOriginalPath = "",
                   tempModPath = "",
                   tempProfilePath = "";

            // We might not have permission to access to the temp directory, so we need to catch the exception.
            try
            {
                tempPath = Directory.CreateDirectory(Path.GetTempPath() + "\\AM2RModPacker").FullName;
                tempOriginalPath = Directory.CreateDirectory(tempPath + "\\original").FullName;
                tempModPath = Directory.CreateDirectory(tempPath + "\\mod").FullName;
                tempProfilePath = Directory.CreateDirectory(tempPath + "\\profile").FullName;
            }
            catch (System.Security.SecurityException)
            {
                MessageBox.Show("Could not create temp directory! Please run the application with administrator rights.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                AbortPatch();

                return;
            }

            // Extract 1.1 and modded AM2R to their own directories in temp work
            ZipFile.ExtractToDirectory(originalPath, tempOriginalPath);
            ZipFile.ExtractToDirectory(input, tempModPath);

            if (Directory.Exists(tempModPath + "\\AM2R"))
                tempModPath += "\\AM2R";

            // Verify 1.1 with an MD5. If it does not match, exit cleanly and provide a warning window.
            try
            {
                string newMD5 = CalculateMD5(tempOriginalPath + "\\data.win");

                if (newMD5 != ORIGINAL_MD5)
                {
                    // Show error box
                    MessageBox.Show("1.1 data.win does not meet MD5 checksum! Mod packaging aborted.\n1.1 MD5: " + ORIGINAL_MD5 + "\nYour MD5: " + newMD5, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    AbortPatch();

                    return;
                }
            }
            catch (FileNotFoundException)
            {
                // Show error message
                MessageBox.Show("data.win not found! Are you sure you selected AM2R 1.1? Mod packaging aborted.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                AbortPatch();

                return;
            }

            // Create AM2R.exe and data.win patches
            if (profile.OperatingSystem == "Windows")
            {
                if (!File.Exists(tempModPath + "/AM2R.exe"))
                {
                    var result = MessageBox.Show("Modded game not found, make sure it's not placed in any subfolders.\nCreated profile will likely not be installable, are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                        AbortPatch();
                }

                if (File.Exists(tempModPath + "profile.xml"))
                {
                    var result = MessageBox.Show("profile.xml found. This file is used by the AM2RLauncher to determine profile stats and its inclusion may make the profile uninstallable. Are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                        AbortPatch();
                }

                if (profile.UsesYYC)
                {
                    CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\AM2R.exe", tempProfilePath + "\\AM2R.xdelta");
                }
                else
                {
                    CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\data.win", tempProfilePath + "\\data.xdelta");

                    CreatePatch(tempOriginalPath + "\\AM2R.exe", tempModPath + "\\AM2R.exe", tempProfilePath + "\\AM2R.xdelta");
                }
            }
            else if (profile.OperatingSystem == "Linux")
            {
                string runnerName = File.Exists(tempModPath + "\\" + "AM2R") ? "AM2R" : "runner";

                if (!File.Exists(tempModPath + "/" + runnerName))
                {
                    var result = MessageBox.Show("Modded Linux game not found, make sure it's not placed in any subfolders.\nCreated profile will likely not be installable, are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                        AbortPatch();
                }

                if (File.Exists(tempModPath + "profile.xml"))
                {
                    var result = MessageBox.Show("profile.xml found. This file is used by the AM2RLauncher to determine profile stats and its inclusion may make the profile uninstallable. Are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                        AbortPatch();
                }

                CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\replacedets\\game.unx", tempProfilePath + "\\game.xdelta");
                CreatePatch(tempOriginalPath + "\\AM2R.exe", tempModPath + "\\" + runnerName, tempProfilePath + "\\AM2R.xdelta");
            }

            // Create game.droid patch and wrapper if Android is supported
            if (profile.Android)
            {
                string tempAndroid = Directory.CreateDirectory(tempPath + "\\android").FullName;

                // Extract APK 
                // - java -jar apktool.jar d "%~dp0AM2RWrapper_old.apk"

                // Process startInfo
                ProcessStartInfo procStartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    WorkingDirectory = tempAndroid,
                    Arguments = "/C java -jar \"" + localPath + "\\utilities\\android\\apktool.jar\" d -f -o \"" + tempAndroid + "\" \"" + apkPath + "\"",
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                // Run process
                using (Process proc = new Process { StartInfo = procStartInfo })
                {
                    proc.Start();

                    proc.WaitForExit();
                }

                // Create game.droid patch
                CreatePatch(tempOriginalPath + "\\data.win", tempAndroid + "\\replacedets\\game.droid", tempProfilePath + "\\droid.xdelta");

                // Delete excess files in APK

                // Create whitelist
                string[] whitelist = { "splash.png", "portrait_splash.png" };

                // Get directory
                DirectoryInfo androidreplacedets = new DirectoryInfo(tempAndroid + "\\replacedets");

                


                // Delete files
                foreach (FileInfo file in androidreplacedets.GetFiles())
                {
                    if (file.Name.EndsWith(".ini") && file.Name != "modifiers.ini")
                    {
                        if (File.Exists(tempProfilePath + "\\AM2R.ini"))
                        {
                            // This shouldn't be a problem... normally...
                            File.Delete(tempProfilePath + "\\AM2R.ini");
                        }
                        File.Copy(file.FullName, tempProfilePath + "\\AM2R.ini");
                    }

                    if (!whitelist.Contains(file.Name))
                    {
                        File.Delete(file.FullName);
                    }
                }

                foreach (DirectoryInfo dir in androidreplacedets.GetDirectories())
                {
                    Directory.Delete(dir.FullName, true);
                }

                // Create wrapper

                // Process startInfo
                // - java -jar apktool.jar b "%~dp0AM2RWrapper_old" -o "%~dp0AM2RWrapper.apk"
                ProcessStartInfo procStartInfo2 = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    WorkingDirectory = tempAndroid,
                    Arguments = "/C java -jar \"" + localPath + "\\utilities\\android\\apktool.jar\" b -f \"" + tempAndroid + "\" -o \"" + tempProfilePath + "\\AM2RWrapper.apk\"",
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                // Run process
                using (Process proc = new Process { StartInfo = procStartInfo2 })
                {
                    proc.Start();

                    proc.WaitForExit();
                }

                string tempAndroidProfilePath = tempProfilePath + "\\android";
                Directory.CreateDirectory(tempAndroidProfilePath);

                File.Move(tempProfilePath + "\\AM2RWrapper.apk", tempAndroidProfilePath + "\\AM2RWrapper.apk");
                if (File.Exists(tempProfilePath + "\\AM2R.ini"))
                    File.Move(tempProfilePath + "\\AM2R.ini", tempAndroidProfilePath + "\\AM2R.ini");
            }

            // Copy datafiles (exclude .ogg if custom music is not selected)

            DirectoryInfo dinfo = new DirectoryInfo(tempModPath);
            if (profile.OperatingSystem == "Linux")
                dinfo = new DirectoryInfo(tempModPath + "\\replacedets");

            Directory.CreateDirectory(tempProfilePath + "\\files_to_copy");

            if (profile.UsesCustomMusic)
            {
                // Copy files, excluding the blacklist
                CopyFilesRecursive(dinfo, DATAFILES_BLACKLIST, tempProfilePath + "\\files_to_copy");
            }
            else
            {
                // Get list of 1.1's music files
                string[] musFiles = Directory.GetFiles(tempOriginalPath, "*.ogg").Select(file => Path.GetFileName(file)).ToArray();

                if (profile.OperatingSystem == "Linux")
                    musFiles = Directory.GetFiles(tempOriginalPath, "*.ogg").Select(file => Path.GetFileName(file).ToLower()).ToArray();


                // Combine musFiles with the known datafiles for a blacklist
                string[] blacklist = musFiles.Concat(DATAFILES_BLACKLIST).ToArray();

                // Copy files, excluding the blacklist
                CopyFilesRecursive(dinfo, blacklist, tempProfilePath + "\\files_to_copy");
            }

            // Export profile as XML
            string xmlOutput = Serializer.Serialize<ModProfileXML>(profile);
            File.WriteAllText(tempProfilePath + "\\profile.xml", xmlOutput);

            // Compress temp folder to .zip
            if (File.Exists(output))
            {
                File.Delete(output);
            }

            ZipFile.CreateFromDirectory(tempProfilePath, output);

            // Delete temp folder
            Directory.Delete(tempPath, true);
        }

19 View Source File : FileService.cs
License : MIT License
Project Creator : amoscardino

public void RenameFiles(List<FileMatch> files)
        {
            foreach (var file in files)
            {
                if (file.NewPath.IsNullOrWhiteSpace())
                    continue;

                Directory.CreateDirectory(Path.GetDirectoryName(file.NewPath));

                File.Move(file.OldPath, file.NewPath);
            }

            _console.WriteLine($"Renamed {files.Count(match => !match.NewPath.IsNullOrWhiteSpace())} files.");
        }

See More Examples