System.IO.Path.GetFileName(string)

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

8810 Examples 7

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

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

            if (info.Version <= CurrentVersion) return;

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

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

            await ShowUpgradeNotificationDialogAsync(info);
        }

19 View Source File : DeploymentManager.cs
License : MIT License
Project Creator : action-bi-toolkit

internal static async Task DeployReportAsync(PbiDeploymentManifest manifest, string label, string environment)
        { 
            if (!manifest.Environments.ContainsKey(environment))
                throw new DeploymentException($"The manifest does not contain the specified environment: {environment}.");

            var deploymentEnv = manifest.Environments[environment];

            if (deploymentEnv.Disabled)
            {
                Log.Warning("Deployment environment '{Environment}' disabled. Aborting.", environment);
                return;
            }

            Log.Information("Starting deployment '{DeploymentLabel}' into environment: {Environment}...", label, environment);

            // Build PBIX

            var tempDir = Environment.ExpandEnvironmentVariables(String.IsNullOrEmpty(manifest.Options.TempDir) ? "%TEMP%" : manifest.Options.TempDir);
            Log.Debug("Using TEMP dir: {TempDir}", tempDir);
            var reportPath = Path.Combine(tempDir, $"{new DirectoryInfo(manifest.Source.Path).Name}.pbix");
            Log.Debug("Creating PBIX from report source at: '{Path}'...", reportPath);

            var model = PbixModel.FromFolder(manifest.Source.Path);

            model.ToFile(reportPath, PowerBI.PbiFileFormat.PBIX);

            // Get auth token

            var app = ConfidentialClientApplicationBuilder
                .Create(Environment.ExpandEnvironmentVariables(manifest.Authentication.ClientId))
                .WithClientSecret(Environment.ExpandEnvironmentVariables(manifest.Authentication.ClientSecret))
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{Environment.ExpandEnvironmentVariables(manifest.Authentication.TenantId)}"))
                // TODO Support custom authority
                .Build();

            string[] scopes = new string[] { $"{POWERBI_API_RESOURCE}/.default" };

            AuthenticationResult result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            var tokenCredentials = new TokenCredentials(result.AccessToken, result.TokenType);
            Log.Information("Access token received. Expires On: {ExpiresOn}", result.ExpiresOn);

            // Use Power BI API to import PBIX

            using (var powerbi = new PowerBIClient(DefaultPowerBIApiBaseUri, tokenCredentials))
            { 
                Import import;
                using (var file = File.OpenRead(reportPath))
                {
                    import = await powerbi.Imports.PostImportWithFileAsyncInGroup(deploymentEnv.WorkspaceId, file,
                        datasetDisplayName: Path.GetFileName(reportPath), // will FAIL without the parameter (although the API marks it as optional)
                        nameConflict: manifest.Options.NameConflict
                    );
                }

                while (import.ImportState != "Succeeded") // Must use magic string here :(
                {
                    if (import.ImportState != null)
                        Log.Information("Import: {Name}, State: {ImportState} (Id: {Id})", import.Name, import.ImportState, import.Id);

                    if (import.ImportState == "Failed")
                        throw new DeploymentException($"Deployment '{import.Name}' ({import.Id}) failed.");

                    await Task.Delay(500);

                    import = await powerbi.Imports.GetImportInGroupAsync(deploymentEnv.WorkspaceId, import.Id);
                }

                Log.Information("Import succeeded: {Id} ({Name})\n\tReport: {ReportId} \"{ReportName}\"\n\tUrl: {WebUrl}"
                    , import.Id
                    , import.Name
                    , import.Reports[0].Id
                    , import.Reports[0].Name
                    , import.Reports[0].WebUrl
                );
                Log.Information("Report Created: {Created}", import.CreatedDateTime);
                Log.Information("Report Updated: {Updated}", import.UpdatedDateTime);
            }
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 5minlab

static void WWWFileHandler(RequestContext context, bool download) {
            string path, type;
            FindFileType(context, download, out path, out type);

            WWW req = new WWW(path);
            while (!req.isDone) {
                Thread.Sleep(0);
            }

            if (string.IsNullOrEmpty(req.error)) {
                context.Response.ContentType = type;
                if (download)
                    context.Response.AddHeader("Content-disposition", string.Format("attachment; filename={0}", Path.GetFileName(path)));

                context.Response.WriteBytes(req.bytes);
                return;
            }

            if (req.error.StartsWith("Couldn't open file")) {
                context.preplaced = true;
            } else {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.StatusDescription = string.Format("Fatal error:\n{0}", req.error);
            }
        }

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

private static System.Version GetPluginVersion(string path)
	{
		System.Version pluginVersion = invalidVersion;

		try
		{
			pluginVersion = new System.Version(Path.GetFileName(path));
		}
		catch
		{
			pluginVersion = invalidVersion;
		}

		if (pluginVersion == invalidVersion)
		{
			//Unable to determine version from path, fallback to Win64 DLL meta data
			path += GetPluginBuildTargetSubPath(PluginPlatform.Win64);
			if (!File.Exists(path))
			{
				path += GetDisabledPluginSuffix();
				if (!File.Exists(path))
				{
					return invalidVersion;
				}
			}

			FileVersionInfo pluginVersionInfo = FileVersionInfo.GetVersionInfo(path);
			if (pluginVersionInfo == null || pluginVersionInfo.ProductVersion == null || pluginVersionInfo.ProductVersion == "")
			{
				return invalidVersion;
			}

			pluginVersion = new System.Version(pluginVersionInfo.ProductVersion);
		}

		return pluginVersion;
	}

19 View Source File : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static MixedRealityToolkitModuleType GetModuleType(string filePath)
        {
            const string sentinelRegexPattern = @"^MRTK\.(?<module>[a-zA-Z]+)\.sentinel";
            string fileName = Path.GetFileName(filePath);
            var matches = Regex.Matches(fileName, sentinelRegexPattern);
            if (matches.Count == 1)
            {
                var moduleName = matches[0].Groups["module"].Value;
                MixedRealityToolkitModuleType moduleType;
                if (moduleNameMap.TryGetValue(moduleName, out moduleType))
                {
                    return moduleType;
                }
            }
            return MixedRealityToolkitModuleType.None;
        }

19 View Source File : StringExtension.cs
License : MIT License
Project Creator : 3F

public static Dictionary<string, string> GetFileProperties(this string file)
        {
            if(string.IsNullOrEmpty(file))
            {
                return new Dictionary<string, string>()
                {
                    [PropertyNames.SLN_DIR]     = PropertyNames.UNDEFINED,
                    [PropertyNames.SLN_EXT]     = PropertyNames.UNDEFINED,
                    [PropertyNames.SLN_FNAME]   = PropertyNames.UNDEFINED,
                    [PropertyNames.SLN_NAME]    = PropertyNames.UNDEFINED,
                    [PropertyNames.SLN_PATH]    = PropertyNames.UNDEFINED,
                };
            }

            return new Dictionary<string, string>()
            {
                [PropertyNames.SLN_DIR]     = GetDirectoryFromFile(file),
                [PropertyNames.SLN_EXT]     = Path.GetExtension(file),
                [PropertyNames.SLN_FNAME]   = Path.GetFileName(file),
                [PropertyNames.SLN_NAME]    = Path.GetFileNameWithoutExtension(file),
                [PropertyNames.SLN_PATH]    = file,
            };
        }

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

private static IEnumerable<BinDirectory> GetBinDirectories(string path)
        {
            return from directory in Directory.GetDirectories(path)
                   let match = BinDirectoryRegex.Match(Path.GetFileName(directory) ?? string.Empty)
                   where match.Success
                   select new BinDirectory(Version.Parse(match.Groups[1].Value), directory);
        }

19 View Source File : MainForm.cs
License : MIT License
Project Creator : 13xforever

private void selectIrdButton_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                CheckFileExists = true,
                DefaultExt = ".ird",
                Filter = "IRD file (*.ird)|*.ird|Redump disc key file (*.dkey)|*.dkey|All supported files|*.ird;*.dkey|All files|*",
                FilterIndex = 2,
                replacedle = "Select a disc key file",
                SupportMultiDottedExtensions = true,
                InitialDirectory = settings.IrdDir,
            };
            var dialogResult = dialog.ShowDialog();
            if (dialogResult != DialogResult.OK || string.IsNullOrEmpty(dialog.FileName) || !File.Exists(dialog.FileName))
                return;

            var discKeyPath = dialog.FileName;
            try
            {
                var discKey = File.ReadAllBytes(discKeyPath);
                DiscKeyInfo keyInfo;
                if (discKey.Length > 256 / 8)
                {
                    var ird = IrdParser.Parse(discKey);
                    keyInfo = new DiscKeyInfo(ird.Data1, null, discKeyPath, KeyType.Ird, ird.Crc32.ToString("x8"));
                }
                else
                    keyInfo = new DiscKeyInfo(null, discKey, discKeyPath, KeyType.Redump, discKey.ToHexString());
                var discKeyFilename = Path.GetFileName(discKeyPath);
                var cacheFilename = Path.Combine(settings.IrdDir, discKeyFilename);
                if (!File.Exists(cacheFilename))
                    File.Copy(discKeyPath, cacheFilename);

                //todo: proper check
                currentDumper.FindDiscKeyAsync(settings.IrdDir).GetAwaiter().GetResult();
                if (!currentDumper.IsValidDiscKey(discKey))
                {
                    MessageBox.Show("Selected disk key file contains incompatible file set, and cannot be used with the selected PS3 game disc.", "IRD file check", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                selectIrdButton.Visible = false;
                selectIrdButton.Enabled = false;
                FindMatchingIrdFinished(sender, new RunWorkerCompletedEventArgs(currentDumper, null, currentDumper?.Cts.IsCancellationRequested ?? true));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "IRD Check Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

19 View Source File : ResourcesSerializer.cs
License : MIT License
Project Creator : action-bi-toolkit

public bool Serialize(IDictionary<string, byte[]> content)
        {
            if (content == null || content.Count == 0) return false;
            foreach (var entry in content)
            {
                // Special handling of 'package.json' to make it readable
                if (Path.GetFileName(entry.Key) == "package.json")
                {
                    try
                    {
                        var json = JObject.Parse(Encoding.UTF8.GetString(entry.Value));
                        _folder.Write(json, entry.Key);
                        continue;
                    }
                    catch (Exception e)
                    {
                        Log.Warning(e, "Failed to parse resource at {Path} as Json object.", entry.Key);
                    }
                }

                _folder.WriteFile(entry.Key, stream =>
                {
                    stream.Write(entry.Value, 0, entry.Value.Length);
                });
            }
        
            return true;
        }

19 View Source File : IrdTests.cs
License : MIT License
Project Creator : 13xforever

[Test, Explicit("Requires custom data")]
        public async Task TocSizeTest()
        {
            var path = @"E:\FakeCDs\PS3 Games\ird";
            var result = new List<(string filename, long size)>();
            foreach (var f in Directory.EnumerateFiles(path, "*.ird", SearchOption.TopDirectoryOnly))
            {
                var bytes = await File.ReadAllBytesAsync(f).ConfigureAwait(false);
                var ird = IrdParser.Parse(bytes);
                using (var header = GetDecompressHeader(ird))
                    result.Add((Path.GetFileName(f), header.Length));
            }
            replacedert.That(result.Count, Is.GreaterThan(0));

            var groupedStats = (from t in result
                    group t by t.size into g
                    select new {size = g.Key, count = g.Count()}
                ).OrderByDescending(i => i.count)
                .ThenByDescending(i => i.size)
                .ToList();

            var largest = groupedStats.Max(i => i.size);
            var largesreplacedem = result.First(i => i.size == largest);
            Console.WriteLine($"Largest TOC: {largesreplacedem.filename} ({largest.replacedtorageUnit()})");

            foreach (var s in groupedStats)
                Console.WriteLine($"{s.count} items of size {s.size}");

            replacedert.That(groupedStats.Count, Is.EqualTo(1));
        }

19 View Source File : FormMain.cs
License : MIT License
Project Creator : Abneed

private void Guardar()
        {

            saveFileDialogDoreplacedento.FileName = tabControlPrincipal.SelectedTab.Name;
            saveFileDialogDoreplacedento.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents);
            saveFileDialogDoreplacedento.Filter = "Formato de texto enriquecido (RTF)|*.rtf";
            saveFileDialogDoreplacedento.replacedle = "Guardar";

            if (saveFileDialogDoreplacedento.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // Si se selecciono un nombre de archivo valido...
                if (saveFileDialogDoreplacedento.FileName.Length > 0)
                {
                    try
                    {
                        // Guarda el contenido del RichTextBox en la ruta del archivo establecida.
                        ObtenerDoreplacedentoActual.SaveFile(saveFileDialogDoreplacedento.FileName, RichTextBoxStreamType.RichText);

                        // Se establece el nombre del archivo en el replacedulo de la pestaña y el nombre de la misma.
                        string NombreArchivo = Path.GetFileName(saveFileDialogDoreplacedento.FileName);
                        tabControlPrincipal.SelectedTab.Text = NombreArchivo;
                        tabControlPrincipal.SelectedTab.Name = NombreArchivo;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }
        }

19 View Source File : EditorProjectUtilities.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

internal static bool FindDirectory(string directoryPathToSearch, string directoryName, out string path)
        {
            path = string.Empty;

            var directories = Directory.GetDirectories(directoryPathToSearch);

            for (int i = 0; i < directories.Length; i++)
            {
                var name = Path.GetFileName(directories[i]);

                if (name != null && name.Equals(directoryName))
                {
                    path = directories[i];
                    return true;
                }

                if (FindDirectory(directories[i], directoryName, out path))
                {
                    return true;
                }
            }

            return false;
        }

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

public static string GetDownloadFileName(string url)
        {
            var fileName = System.IO.Path.GetFileName(url);
            fileName += "_temp";

            return fileName;
        }

19 View Source File : FSExtensions.cs
License : Apache License 2.0
Project Creator : acblog

public static void CopyDirectory(string sourceDirPath, string saveDirPath)
        {
            if (!Directory.Exists(saveDirPath))
            {
                Directory.CreateDirectory(saveDirPath);
            }
            string[] files = Directory.GetFiles(sourceDirPath);

            foreach (string file in files)
            {
                string pFilePath = Path.Join(saveDirPath, Path.GetFileName(file));
                File.Copy(file, pFilePath, true);
            }

            string[] dirs = Directory.GetDirectories(sourceDirPath);
            foreach (string dir in dirs)
            {
                CopyDirectory(dir, Path.Join(saveDirPath, Path.GetFileName(dir)));
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 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 View Source File : ConfigManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Initialize(string path = @"Config.js")
        {
            var directoryName = Path.GetDirectoryName(path);
            var fileName = Path.GetFileName(path) ?? "Config.js";

            string pathToUse;

            // If no directory was specified, try both the current directory and the startup directory
            if (string.IsNullOrWhiteSpace(directoryName))
            {
                directoryName = Environment.CurrentDirectory;

                pathToUse = Path.Combine(directoryName, fileName);

                if (!File.Exists(pathToUse))
                {
                    // File not found in Environment.CurrentDirectory
                    // Lets try the Executingreplacedembly Location
                    var executingreplacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;

                    directoryName = Path.GetDirectoryName(executingreplacedemblyLocation);

                    if (directoryName != null)
                        pathToUse = Path.Combine(directoryName, fileName);
                }
            }
            else
            {
                pathToUse = path;
            }

            try
            {
                if (!File.Exists(pathToUse))
                {
                    Console.WriteLine("Configuration file is missing.  Please copy the file Config.js.example to Config.js and edit it to match your needs before running ACE.");
                    throw new Exception("missing configuration file");
                }

                var fileText = File.ReadAllText(pathToUse);

                Config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));
            }
            catch (Exception exception)
            {
                Console.WriteLine("An exception occured while loading the configuration file!");
                Console.WriteLine($"Exception: {exception.Message}");

                // environment.exit swallows this exception for testing purposes.  we want to expose it.
                throw;
            }
        }

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

public static void WriteFile(this HttpListenerResponse response, string path, string type = "application/octet-stream", bool download = false) {
            using (FileStream fs = File.OpenRead(path)) {
                response.StatusCode = (int)HttpStatusCode.OK;
                response.StatusDescription = "OK";
                response.ContentLength64 = fs.Length;
                response.ContentType = type;
                if (download)
                    response.AddHeader("Content-disposition", string.Format("attachment; filename={0}", Path.GetFileName(path)));

                byte[] buffer = new byte[64 * 1024];
                int read;
                while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) {
                    // FIXME required?
                    System.Threading.Thread.Sleep(0);
                    response.OutputStream.Write(buffer, 0, read);
                }
            }
        }

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

protected static T FolderElementPipe<T>(T element, XElement node, FolderElement parent) where T : FolderElement
        {
            element = FileElementPipe(element, node, parent);

            if (!node.HasElements)
            {
                element.Source = Path.Combine(
                    parent.Source,
                    Path.GetFileName(element.Target ?? throw new InvalidOperationException()));
            }

            element.Files = node
                .Elements(FileTag)
                .Select(item => FileElement.Create(item, element))
                .ToList();

            element.Folders = node
                .Elements(FolderTag)
                .Select(item => Create(item, element))
                .ToList();

            return element;
        }

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 : DependencyResolverTests.cs
License : MIT License
Project Creator : action-bi-toolkit

[Fact]
        public void Can_get_msmdsrv_path()
        {
            if (_fixture.DependenciesResolver.TryFindMsmdsrv(out var path))
            {
                replacedert.True(File.Exists(path));
                replacedert.Equal("msmdsrv.exe", Path.GetFileName(path).ToLower());
            }
            else
            {
                replacedert.True(false, "Could not find msmdsrv.exe");
            }
        }

19 View Source File : dlgCloneVM.cs
License : MIT License
Project Creator : 86Box

private void dlgCloneVM_Load(object sender, EventArgs e)
        {
            lblPath1.Text = main.cfgpath;
            lblOldVM.Text = "Virtual machine \"" + Path.GetFileName(oldPath) + "\" will be cloned into:";
        }

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

private async void Flash()
        {
            await Task.Delay(1000);
FileMode:
            CreateRequest("Device software installation", "You are installing software on your device, you can choose where to get it from.", 
                "Get the latest image from the Internet (Recommended)", "Use a local image on this PC", out int option);

            if (option == 2)
            {
                Invoke(new Action(() =>
                {
                    OpenFileDialog fileDialog = new OpenFileDialog()
                    {
                        Multiselect = false,
                        SupportMultiDottedExtensions = true,
                        Filter = "Binary files (*.bin)|*.bin|Hex files (*.hex)|*.hex|All files (*.*)|*.*",
                        replacedle = "Choose a software image file",
                    };

                    if (fileDialog.ShowDialog() == DialogResult.OK)
                        Program.Settings.Bin = fileDialog.FileName;
                }));

                if (Program.Settings.Bin == default)
                    goto FileMode;
            }
            else if (option == 1)
            {
                if (!CreateSelRequest(out string file))
                    goto FileMode;
                else
                {
                    WaitFm.Debug($"User selected file: {file}");

                    WaitFm.replacedle("Downloading software");
                    WaitFm.Caption("");

                    WaitFm.Debug($"Downloading {file}...");

                    try
                    {
                        WebClient client = new WebClient();

                        client.DownloadProgressChanged += (s, e) =>
                        {
                            WaitFm.Caption($"Downloading {Path.GetFileName(file)} from github.com ({e.ProgressPercentage}%)");
                        };
                        client.DownloadFileCompleted += delegate
                        {
                            WaitFm.Debug($"Successfully downloaded {Path.GetFileName(file)} from github.com", Event.Success);
                        };

                        await client.DownloadFileTaskAsync(file, Path.GetFileName(file));
                        Program.Settings.Bin = Path.GetFileName(file);
                    }
                    catch (Exception ex)
                    {
                        WaitFm.Debug($"Download failed due to an error: {ex.Message}", Event.Critical);
                        await CreateMessage("A problem was encountered", "The required file could not be downloaded. You can try again.");

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();
                        return;
                    }          
                }

                WaitFm.replacedle("Getting ready");
                await Task.Delay(1000);
            }
            else
                throw new Exception($"The selection could not be determined due to an invalid value. {option}");

            CreateRequest("Flash Operation", "The program is about to install software to your Espressif device. " +
                    "Existing data on the device will be PERMANENTLY DELETED, are you sure?", "Allow software installation",
                    "Cancel flash operation, no changes will be made", out int result);

            if (result == 2)
            {
                WaitFm.Debug("User cancelled the flash operation.", Event.Critical);
                await CreateMessage("Software installation aborted", "You've chosen to cancel the installation " +
                    "of software to your Espressif device. No changes have been made. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
            else if (result == 1)
            {
                WaitFm.Debug("Flash operation started.");
                WaitFm.replacedle("Installing software");

                WaitFm.Caption("Checking device connection");
                WaitFm.Debug("Checking device connection...");

                if (!Program.Settings.PortFix)
                    WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");

                string output = string.Empty;

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);

                        WaitFm.Caption("Connection was successful");
                    }
                    else
                        throw new Exception("Could not connect to the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);

                        WaitFm.Caption("Connection was successful");
                    }
                    else
                        throw new Exception("Could not connect to the device.");
                }

                WaitFm.Caption("Erasing flash memory");
                WaitFm.Debug("Erasing flash memory chip...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to erase the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to erase the device.");
                }

                WaitFm.Caption("Writing new software image");
                WaitFm.Debug("Writing new software image...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
                    {
                        WaitFm.Debug("Flash complete!", Event.Success);
                        WaitFm.Caption("Installed.");
                    }
                    else
                        throw new Exception("Failed to flash the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to flash the device.");
                }


                await Task.Delay(500);

                await CreateMessage("Installation complete", $"The software package {Program.Settings.Bin} has been successfully" +
                    $" installed on your device. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
            else
            {
                WaitFm.Debug("Failsafe: the selection was invalid.", Event.Critical);
                await CreateMessage("Software installation aborted", "A problem was encountered with the selection. " +
                    "No changes have been made to your Espressif device. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
        }

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 : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static bool IsSentinelFile(string replacedetPath)
        {
            return Regex.IsMatch(Path.GetFileName(replacedetPath), SentinelFilePattern);
        }

19 View Source File : ModuleCollection.cs
License : MIT License
Project Creator : 17MKH

public void Load()
    {
        var modulesRootPath = Path.Combine(AppContext.BaseDirectory, Constants.ROOT_DIR);
        if (!Directory.Exists(modulesRootPath))
            return;

        var moduleDirs = Directory.GetDirectories(modulesRootPath);
        if (!moduleDirs.Any())
            return;

        _replacedemblyHelper = new replacedemblyHelper();
        var optionsList = new List<ModuleOptions>();
        foreach (var dir in moduleDirs)
        {
            var code = Path.GetFileName(dir)!.Split("_")[1];
            var options = _configuration.Get<ModuleOptions>($"Mkh:Modules:{code}");
            if (options.Db != null)
            {
                options.Code = code;
                options.Dir = dir;
                optionsList.Add(options);
            }
        }

        foreach (var options in optionsList.OrderBy(m => m.Sort))
        {
            LoadModule(options);
        }

        //释放资源
        _replacedemblyHelper = null;
    }

19 View Source File : FormMain.cs
License : MIT License
Project Creator : Abneed

private void Abrir()
        {
            openFileDialogDoreplacedento.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents);
            openFileDialogDoreplacedento.Filter = "Formato de texto enriquecido (RTF)|*.rtf";

            if (openFileDialogDoreplacedento.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // Si se selecciono un nombre de archivo valido...
                if (openFileDialogDoreplacedento.FileName.Length > 0)
                {
                    try
                    {
                        // Se genera una nueva pestaña.
                        AgregarPestana();

                        // Se busca y se selecciona la nueva pestaña generada.
                        tabControlPrincipal.SelectedTab = tabControlPrincipal.TabPages["Sin título-" + this.m_intConteoPestanas];

                        // Carga el contenido del archivo en el RichTextBox de la nueva pestaña.
                        ObtenerDoreplacedentoActual.LoadFile(openFileDialogDoreplacedento.FileName, RichTextBoxStreamType.RichText);
                        
                        // Se establece el nombre del archivo en el replacedulo de la pestaña y el nombre de la misma.
                        string NombreArchivo = Path.GetFileName(openFileDialogDoreplacedento.FileName);
                        tabControlPrincipal.SelectedTab.Text = NombreArchivo;
                        tabControlPrincipal.SelectedTab.Name = NombreArchivo;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }
        }

19 View Source File : DevicePortal.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static async Task<bool> InstallAppAsync(string appFullPath, DeviceInfo targetDevice, bool waitForDone = true)
        {
            Debug.replacedert(!string.IsNullOrEmpty(appFullPath));
            var isAuth = await EnsureAuthenticationAsync(targetDevice);
            if (!isAuth) 
            { 
                return false; 
            }

            Debug.Log($"Starting app install on {targetDevice.ToString()}...");

            // Calculate the cert and dependency paths
            string fileName = Path.GetFileName(appFullPath);
            string certFullPath = Path.ChangeExtension(appFullPath, ".cer");
            string certName = Path.GetFileName(certFullPath);

            string arch = "ARM";
            if (appFullPath.Contains("x86"))
            {
                arch = "x86";
            }
            else if (appFullPath.Contains("ARM64"))
            {
                arch = "ARM64";
            }

            string depPath = [email protected]"{Path.GetDirectoryName(appFullPath)}\Dependencies\{arch}\";

            var form = new WWWForm();

            try
            {
                // APPX file
                Debug.replacedert(appFullPath != null);
                using (var stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName);
                    }
                }

                // CERT file
                Debug.replacedert(certFullPath != null);
                using (var stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName);
                    }
                }

                // Dependencies
                IOFileInfo[] depFiles = new DirectoryInfo(depPath).GetFiles();
                foreach (IOFileInfo dep in depFiles)
                {
                    using (var stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (var reader = new BinaryReader(stream))
                        {
                            string depFilename = Path.GetFileName(dep.FullName);
                            form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                return false;
            }

            // Query
            string query = $"{string.Format(InstallQuery, FinalizeUrl(targetDevice.IP))}?package={UnityWebRequest.EscapeURL(fileName)}";

            var response = await Rest.PostAsync(query, form, targetDevice.Authorization);

            if (!response.Successful)
            {
                if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
                {
                    return await InstallAppAsync(appFullPath, targetDevice, waitForDone);
                }

                Debug.LogError($"Failed to install {fileName} on {targetDevice.ToString()}.");
                return false;
            }

            var status = AppInstallStatus.Installing;

            // Wait for done (if requested)
            while (waitForDone && status == AppInstallStatus.Installing)
            {
                status = await GetInstallStatusAsync(targetDevice);

                switch (status)
                {
                    case AppInstallStatus.InstallSuccess:
                        Debug.Log($"Successfully installed {fileName} on {targetDevice.ToString()}.");
                        return true;
                    case AppInstallStatus.InstallFail:
                        Debug.LogError($"Failed to install {fileName} on {targetDevice.ToString()}.");
                        return false;
                }
            }

            return true;
        }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : 214175590

public static void CopyDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
                return;

            if (!Directory.Exists(toDir))
            {
                Directory.CreateDirectory(toDir);
            }

            string[] files = Directory.GetFiles(fromDir);
            foreach (string formFileName in files)
            {
                string fileName = Path.GetFileName(formFileName);
                string toFileName = Path.Combine(toDir, fileName);
                File.Copy(formFileName, toFileName);
            }
            string[] fromDirs = Directory.GetDirectories(fromDir);
            foreach (string fromDirName in fromDirs)
            {
                string dirName = Path.GetFileName(fromDirName);
                string toDirName = Path.Combine(toDir, dirName);
                CopyDir(fromDirName, toDirName);
            }
        }

19 View Source File : FormMain.cs
License : MIT License
Project Creator : Abneed

private void GuardarComo()
        {
            saveFileDialogDoreplacedento.FileName = tabControlPrincipal.SelectedTab.Name;
            saveFileDialogDoreplacedento.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents);
            saveFileDialogDoreplacedento.Filter = "Formato de texto enriquecido (RTF)|*.rtf";
            saveFileDialogDoreplacedento.replacedle = "Guardar como";

            if (saveFileDialogDoreplacedento.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // Si se selecciono un nombre de archivo valido...
                if (saveFileDialogDoreplacedento.FileName.Length > 0)
                {
                    try
                    {
                        // Guarda el contenido del RichTextBox en la ruta del archivo establecida.
                        ObtenerDoreplacedentoActual.SaveFile(saveFileDialogDoreplacedento.FileName, RichTextBoxStreamType.RichText);

                        // Se establece el nombre del archivo en el replacedulo de la pestaña y el nombre de la misma.
                        string NombreArchivo = Path.GetFileName(saveFileDialogDoreplacedento.FileName);
                        tabControlPrincipal.SelectedTab.Text = NombreArchivo;
                        tabControlPrincipal.SelectedTab.Name = NombreArchivo;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }

        }

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 : OVRCubemapCapture.cs
License : MIT License
Project Creator : absurd-joy

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

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

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

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

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

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


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

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

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

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

		DestroyImmediate(tex);
		return true;
	}

19 View Source File : SlnTest.cs
License : MIT License
Project Creator : 3F

[Fact]
        public void SlnResultTest1()
        {
            using(var sln = new Sln(SlnItems.Projects, SlnSamplesResource.vsSolutionBuildEvent))
            {
                replacedert.Equal("\\", sln.Result.SolutionDir);
                replacedert.Equal(SlnParser.MEM_FILE, sln.Result.Properties[PropertyNames.SLN_PATH]);

                replacedert.Equal(sln.Result.SolutionDir, sln.Result.Properties[PropertyNames.SLN_DIR]);
                replacedert.Equal(Path.GetExtension(SlnParser.MEM_FILE), sln.Result.Properties[PropertyNames.SLN_EXT]);
                replacedert.Equal(Path.GetFileName(SlnParser.MEM_FILE), sln.Result.Properties[PropertyNames.SLN_FNAME]);
                replacedert.Equal(Path.GetFileNameWithoutExtension(SlnParser.MEM_FILE), sln.Result.Properties[PropertyNames.SLN_NAME]);
                replacedert.Null(sln.Result.Properties[PropertyNames.CONFIG]);
                replacedert.Null(sln.Result.Properties[PropertyNames.PLATFORM]);
            }
        }

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

private static string GetModuleInfoRef(string installPath)
        {
            var dllFilePath = Directory
                .GetFiles(installPath)
                .FirstOrDefault(item => ModuleFileRegex.IsMatch(Path.GetFileName(item)));

            return $"file:///{dllFilePath}";
        }

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 : UpgradeTaskBase.cs
License : MIT License
Project Creator : Accelerider

protected virtual IEnumerable<(Version Version, string Path)> GetLocalVersions()
        {
            return from folderPath in Directory.GetDirectories(InstallDirectory)
                   let folderName = Path.GetFileName(folderPath)
                   where !string.IsNullOrEmpty(folderName)
                   let match = _versionRegex.Match(folderName)
                   where match.Success
                   select (Version.Parse(match.Groups[1].Value), folderPath);
        }

19 View Source File : WebContentFolderHelper.cs
License : MIT License
Project Creator : 52ABP

private static bool DirectoryContains(string directory, string fileName)
        {
            return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
        }

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

public static bool CreateHardLinkTo(this string @this, string targetPath)
        {
            if (File.Exists(targetPath) || Directory.Exists(targetPath)) throw new IOException("Cannot create an existing file or directory. ");

            if (File.Exists(@this))
            {
                return CreateHardLink(targetPath, @this, IntPtr.Zero);
            }

            if (Directory.Exists(@this))
            {
                var entries = Directory.GetFileSystemEntries(@this);
                Directory.CreateDirectory(targetPath);

                // Recursion
                return entries.All(item => item.CreateHardLinkTo(Path.Combine(targetPath, Path.GetFileName(item))));
            }

            throw new FileNotFoundException();
        }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

public async Task FindDiscKeyAsync(string discKeyCachePath)
        {
            // reload disc keys
            try
            {
                foreach (var keyProvider in DiscKeyProviders)
                {
                    Log.Trace($"Getting keys from {keyProvider.GetType().Name}...");
                    var newKeys = await keyProvider.EnumerateAsync(discKeyCachePath, ProductCode, Cts.Token).ConfigureAwait(false);
                    Log.Trace($"Got {newKeys.Count} keys");
                    lock (AllKnownDiscKeys)
                    {
                        foreach (var keyInfo in newKeys)
                        {
                            try
                            {
                                if (!AllKnownDiscKeys.TryGetValue(keyInfo.DecryptedKeyId, out var duplicates))
                                    AllKnownDiscKeys[keyInfo.DecryptedKeyId] = duplicates = new HashSet<DiscKeyInfo>();
                                duplicates.Add(keyInfo);
                            }
                            catch (Exception e)
                            {
                                Log.Error(e);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to load disc keys");
            }
            // check if user provided something new since the last attempt
            var untestedKeys = new HashSet<string>();
            lock (AllKnownDiscKeys)
                untestedKeys.UnionWith(AllKnownDiscKeys.Keys);
            untestedKeys.ExceptWith(TestedDiscKeys);
            if (untestedKeys.Count == 0)
                throw new KeyNotFoundException("No valid disc decryption key was found");

            // select physical device
            string physicalDevice = null;
            List<string> physicalDrives = new List<string>();
            Log.Trace("Trying to enumerate physical drives...");
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    physicalDrives = EnumeratePhysicalDrivesWindows();
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    physicalDrives = EnumeratePhysicalDrivesLinux();
                else
                    throw new NotImplementedException("Current OS is not supported");
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
            Log.Debug($"Found {physicalDrives.Count} physical drives");

            if (physicalDrives.Count == 0)
                throw new InvalidOperationException("No optical drives were found");

            foreach (var drive in physicalDrives)
            {
                try
                {
                    Log.Trace($"Checking physical drive {drive}...");
                    using var discStream = File.Open(drive, FileMode.Open, FileAccess.Read, FileShare.Read);
                    var tmpDiscReader = new CDReader(discStream, true, true);
                    if (tmpDiscReader.FileExists("PS3_DISC.SFB"))
                    {
                        Log.Trace("Found PS3_DISC.SFB, getting sector data...");
                        var discSfbInfo = tmpDiscReader.GetFileInfo("PS3_DISC.SFB");
                        if (discSfbInfo.Length == discSfbData.Length)
                        {
                            var buf = new byte[discSfbData.Length];
                            var sector = tmpDiscReader.PathToClusters(discSfbInfo.FullName).First().Offset;
                            Log.Trace($"PS3_DISC.SFB sector number is {sector}, reading content...");
                            discStream.Seek(sector * tmpDiscReader.ClusterSize, SeekOrigin.Begin);
                            discStream.ReadExact(buf, 0, buf.Length);
                            if (buf.SequenceEqual(discSfbData))
                            {
                                physicalDevice = drive;
                                break;
                            }
                            Log.Trace("SFB content check failed, skipping the drive");
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Debug($"Skipping drive {drive}: {e.Message}");
                }
            }
            if (physicalDevice == null)
                throw new AccessViolationException("Couldn't get physical access to the drive");

            Log.Debug($"Selected physical drive {physicalDevice}");
            driveStream = File.Open(physicalDevice, FileMode.Open, FileAccess.Read, FileShare.Read);

            // find disc license file
            discReader = new CDReader(driveStream, true, true);
            FileRecord detectionRecord = null;
            byte[] expectedBytes = null;
            try
            {
                foreach (var path in Detectors.Keys)
                    if (discReader.FileExists(path))
                    {
                        var clusterRange = discReader.PathToClusters(path);
                        detectionRecord = new FileRecord(path, clusterRange.Min(r => r.Offset), discReader.GetFileLength(path));
                        expectedBytes = Detectors[path];
                        if (detectionRecord.Length == 0)
                            continue;
                        
                        Log.Debug($"Using {path} for disc key detection");
                        break;
                    }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            if (detectionRecord == null)
                throw new FileNotFoundException("Couldn't find a single disc key detection file, please report");

            if (Cts.IsCancellationRequested)
                return;

            SectorSize = discReader.ClusterSize;

            // select decryption key
            driveStream.Seek(detectionRecord.StartSector * discReader.ClusterSize, SeekOrigin.Begin);
            detectionSector = new byte[discReader.ClusterSize];
            detectionBytesExpected = expectedBytes;
            sectorIV = Decrypter.GetSectorIV(detectionRecord.StartSector);
            Log.Debug($"Initialized {nameof(sectorIV)} ({sectorIV?.Length * 8} bit) for sector {detectionRecord.StartSector}: {sectorIV?.ToHexString()}");
            driveStream.ReadExact(detectionSector, 0, detectionSector.Length);
            string discKey = null;
            try
            {
                discKey = untestedKeys.AsParallel().FirstOrDefault(k => !Cts.IsCancellationRequested && IsValidDiscKey(k));
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            if (discKey == null)
                throw new KeyNotFoundException("No valid disc decryption key was found");

            if (Cts.IsCancellationRequested)
                return;

            lock (AllKnownDiscKeys)
                AllKnownDiscKeys.TryGetValue(discKey, out allMatchingKeys);
            var discKeyInfo = allMatchingKeys?.First();
            DiscKeyFilename = Path.GetFileName(discKeyInfo?.FullPath);
            DiscKeyType = discKeyInfo?.KeyType ?? default;
        }

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

public static void CopyTo(this string source, string target)
        {
            if (File.Exists(source))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(target));

                File.Copy(source, target, true);
            }
            else if (Directory.Exists(source))
            {
                Directory.CreateDirectory(target);

                Directory.GetFileSystemEntries(source)
                    .ForEach(item => item.CopyTo(Path.Combine(target, Path.GetFileName(item))));
            }
            else
            {
                Print.Error($"Missing {source}!");
            }
        }

19 View Source File : SyntaxTreeFixerEditor.cs
License : MIT License
Project Creator : 71

protected override void Initialize(CSharpCompilation oldCompilation, CancellationToken _)
        {
            OptimizationLevel compilationConfiguration = oldCompilation.Options.OptimizationLevel;

            if (compilationConfiguration == OptimizationLevel.Debug && !runInDebug)
                return;
            if (compilationConfiguration == OptimizationLevel.Release && !runInRelease)
                return;

            CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
            {
                int syntaxTreesLength  = compilation.SyntaxTrees.Length;
                string randomDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                for (int i = 0; i < syntaxTreesLength; i++)
                {
                    SyntaxTree tree = compilation.SyntaxTrees[i];
                    SyntaxTree nextTree = tree;

                    string treePath = tree.FilePath;

                    SourceText source = null;

                    if (nextTree.Encoding == null)
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (StreamWriter writer = new StreamWriter(ms, Encoding.UTF8, 4096, leaveOpen: true))
                            {
                                nextTree.GetText(cancellationToken).Write(writer, cancellationToken);
                            }

                            ms.Position = 0;

                            using (StreamReader reader = new StreamReader(ms, Encoding.UTF8, false, 4096, leaveOpen: true))
                            {
                                source = SourceText.From(reader, (int)ms.Length, Encoding.UTF8);

                                nextTree = nextTree.WithChangedText(source);
                            }
                        }
                    }

                    if (treePath != null && oldCompilation.SyntaxTrees.FirstOrDefault(x => x.FilePath == treePath) == tree)
                    {
                        // The tree already exists as a file, and is the one the user has;
                        // we don't need to change anything.

                        if (source == null)
                            // No changes applied
                            continue;

                        goto Replace;
                    }

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

                    // The tree does not exist or has been changed by an editor,
                    // we need to change its filepath, and write a new file.
                    string newPath = string.IsNullOrEmpty(treePath)
                        ? Path.Combine(randomDirectory, Path.GetRandomFileName() + ".cs")
                        : Path.Combine(randomDirectory, Path.GetFileName(treePath));

                    nextTree = nextTree.WithFilePath(newPath);

                    using (FileStream fs = File.Open(newPath, FileMode.Create, FileAccess.Write))
                    using (StreamWriter writer = new StreamWriter(fs, nextTree.Encoding, 4096))
                    {
                        if (source == null)
                            source = nextTree.GetText(cancellationToken);

                        source.Write(writer, cancellationToken);
                    }

                    Replace:
                    compilation = compilation.ReplaceSyntaxTree(tree, nextTree);
                }

                return compilation;
            }

            CompilationPipeline += EditCompilation;
        }

19 View Source File : CmdLineActions.cs
License : MIT License
Project Creator : action-bi-toolkit

[ArgActionMethod, ArgShortcut("cache"), ArgDescription("Manages the internal replacedembly cache.")]
        [ArgExample("pbi-tools.exe cache list", "Lists all cache folders present in the current user profile.")]
        public void Cache(
            [ArgRequired, ArgDescription("The cache action to perform.")] CacheAction action
        )
        {
            var folders = Directory.GetDirectories(ApplicationFolders.AppDataFolder);
            
            switch (action)
            {
                case CacheAction.List:
                    Array.ForEach(folders, f =>
                        Console.WriteLine($"- {Path.GetFileName(f)}")
                    );
                    break;
                case CacheAction.ClearAll:
                    Array.ForEach(folders, f => 
                    {
                        Directory.Delete(f, recursive: true);
                        Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
                    });
                    break;
                case CacheAction.ClearOutdated:
                    Array.ForEach(folders.OrderByDescending(x => x).Skip(1).ToArray(), f => 
                    {
                        Directory.Delete(f, recursive: true);
                        Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
                    });
                    break;
            }
        }

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

public override void CopyTo(UserData other) {
            using UserDataBatchContext batch = other.OpenBatch();
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);

                Dictionary<string, Type?> types = new();
                replacedembly[] asms = AppDomain.CurrentDomain.Getreplacedemblies();

                foreach (string uid in GetAll()) {
                    PrivateUserInfo info = Load<PrivateUserInfo>(uid);
                    other.Insert(uid, info.Key, info.KeyFull, !info.KeyFull.IsNullOrEmpty());

                    foreach (string path in Directory.GetFiles(Path.Combine(UserRoot, uid))) {
                        string name = Path.GetFileNameWithoutExtension(path);
                        if (name == typeof(PrivateUserInfo).FullName)
                            continue;

                        if (!types.TryGetValue(name, out Type? type)) {
                            foreach (replacedembly asm in asms)
                                if ((type = asm.GetType(name)) != null)
                                    break;
                            types[name] = type;
                        }

                        using Stream stream = File.OpenRead(path);
                        other.InsertData(uid, name, type, stream);
                    }

                    string dir = Path.Combine(UserRoot, uid, "data");
                    if (Directory.Exists(dir)) {
                        foreach (string path in Directory.GetFiles(dir)) {
                            string name = Path.GetFileName(path);
                            using Stream stream = File.OpenRead(path);
                            other.InsertFile(uid, name, stream);
                        }
                    }
                }
            }
        }

19 View Source File : ProjectFolder.cs
License : MIT License
Project Creator : action-bi-toolkit

public IEnumerable<IProjectFolder> GetSubfolders(string searchPattern, SearchOption searchOption) =>
            this.Exists()
            ? Directory.EnumerateDirectories(this.BasePath, searchPattern, searchOption).Select(dir => this.GetSubfolder(Path.GetFileName(dir)))
            : new IProjectFolder[0];

19 View Source File : dlgAddVM.cs
License : MIT License
Project Creator : 86Box

private void btnBrowse_Click(object sender, EventArgs e)
        {
            FolderSelectDialog dialog = new FolderSelectDialog
            {
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer),
                replacedle = "Select a folder where your virtual machines (configs, nvr folders, etc.) will be located"
            };

            if (dialog.Show(Handle))
            {
                txtImportPath.Text = dialog.FileName;
                txtName.Text = Path.GetFileName(dialog.FileName);
            }
        }

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

public override string[] GetAll()
            => !Directory.Exists(UserRoot) ? Dummy<string>.EmptyArray : Directory.GetDirectories(UserRoot).Select(name => Path.GetFileName(name)).ToArray();

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

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

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

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

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

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

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

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

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

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

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

            decryptProgress.Maximum = Program.encryptedFiles.Count;

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

                    // Do Decrypt

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

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

19 View Source File : FileSystemHelper.cs
License : zlib License
Project Creator : 0x0ade

public static string GetNext(string[] possible, string next) {
            if (possible == null)
                return null;
            for (int pi = 0; pi < possible.Length; pi++) {
                string possibleName = Path.GetFileName(possible[pi]);
                if (string.Equals(next, possibleName, StringComparison.InvariantCultureIgnoreCase))
                    return possibleName;
            }
            return null;
        }

19 View Source File : DiscordRPforVSPackage.cs
License : GNU Affero General Public License v3.0
Project Creator : 1thenikita

public async System.Threading.Tasks.Task UpdatePresenceAsync(Doreplacedent doreplacedent, Boolean overrideTimestampReset = false)
        {
            try
            {
                await this.JoinableTaskFactory.SwitchToMainThreadAsync();

                if (!Settings.enabled)
                {
                    if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                        if (!this.Discord.Initialize())
                            ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");

                    this.Discord.ClearPresence();
                    return;
                }

                this.Presence.Details = this.Presence.State = this.replacedets.LargeImageKey = this.replacedets.LargeImageText = this.replacedets.SmallImageKey = this.replacedets.SmallImageText = String.Empty;

                if (Settings.secretMode)
                {
                    this.Presence.Details = Translates.PresenceDetails(Settings.Default.translates);
                    this.Presence.State = Translates.PresenceState(Settings.Default.translates);
                    this.replacedets.LargeImageKey = this.versionImageKey;
                    this.replacedets.LargeImageText = this.versionString;
                    this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
                    goto finish;
                }

                this.Presence.Details = this.Presence.State = "";
                String[] language = Array.Empty<String>();

                if (doreplacedent != null)
                {
                    String filename = Path.GetFileName(path: doreplacedent.FullName).ToUpperInvariant(), ext = Path.GetExtension(filename);
                    List<KeyValuePair<String[], String[]>> list = Constants.Languages.Where(lang => Array.IndexOf(lang.Key, filename) > -1 || Array.IndexOf(lang.Key, ext) > -1).ToList();
                    language = list.Count > 0 ? list[0].Value : Array.Empty<String>();
                }

                Boolean supported = language.Length > 0;
                this.replacedets.LargeImageKey = Settings.largeLanguage ? supported ? language[0] : "text" : this.versionImageKey;
                this.replacedets.LargeImageText = Settings.largeLanguage ? supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates) : this.versionString;
                this.replacedets.SmallImageKey = Settings.largeLanguage ? this.versionImageKey : supported ? language[0] : "text";
                this.replacedets.SmallImageText = Settings.largeLanguage ? this.versionString : supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates);

                if (Settings.showFileName)
                    this.Presence.Details = !(doreplacedent is null) ? Path.GetFileName(doreplacedent.FullName) : Translates.NoFile(Settings.Default.translates);

                if (Settings.showSolutionName)
                {
                    Boolean idling = ide.Solution is null || String.IsNullOrEmpty(ide.Solution.FullName);
                    this.Presence.State = idling ? Translates.Idling(Settings.Default.translates) : $"{Translates.Developing(Settings.Default.translates)} {Path.GetFileNameWithoutExtension(ide.Solution.FileName)}";

                    if (idling)
                    {
                        this.replacedets.LargeImageKey = this.versionImageKey;
                        this.replacedets.LargeImageText = this.versionString;
                        this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
                    }
                }

                if (Settings.showTimestamp && doreplacedent != null)
                {
                    if (!this.InitializedTimestamp)
                    {
                        this.InitialTimestamps = this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
                        this.InitializedTimestamp = true;
                    }

                    if (Settings.resetTimestamp && !overrideTimestampReset)
                        this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
                    else if (Settings.resetTimestamp && overrideTimestampReset)
                        this.Presence.Timestamps = this.CurrentTimestamps;
                    else if (!Settings.resetTimestamp && !overrideTimestampReset)
                        this.Presence.Timestamps = this.InitialTimestamps;

                    this.CurrentTimestamps = this.Presence.Timestamps;
                }

                finish:;
                this.Presence.replacedets = this.replacedets;

                if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                    if (!this.Discord.Initialize())
                        ActivityLog.LogError("DiscordRPforVS", Translates.LogError(Settings.Default.translates));

                this.Discord.SetPresence(this.Presence);
            }
            catch (ArgumentException e)
            {
                ActivityLog.LogError(e.Source, e.Message);
            }
        }

19 View Source File : InputSimulationWindow.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void SaveAnimation(bool loadAfterExport)
        {
            string outputPath;
            if (loadedFilePath.Length > 0)
            {
                string loadedDirectory = Path.GetDirectoryName(loadedFilePath);
                outputPath = EditorUtility.SaveFilePanel(
                    "Select output path",
                    loadedDirectory,
                    InputAnimationSerializationUtils.GetOutputFilename(),
                    InputAnimationSerializationUtils.Extension);
            }
            else
            {
                outputPath = EditorUtility.SaveFilePanelInProject(
                    "Select output path",
                    InputAnimationSerializationUtils.GetOutputFilename(),
                    InputAnimationSerializationUtils.Extension,
                    "Enter filename for exporting input animation");
            }

            if (outputPath.Length > 0)
            {
                string filename = Path.GetFileName(outputPath);
                string directory = Path.GetDirectoryName(outputPath);

                string result = RecordingService.SaveInputAnimation(filename, directory);
                RecordingService.DiscardRecordedInput();

                if (loadAfterExport)
                {
                    LoadAnimation(result);
                }
            }
        }

See More Examples