System.IO.Path.ChangeExtension(string, string)

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

1453 Examples 7

19 View Source File : egsTools.cs
License : Apache License 2.0
Project Creator : AntonioDePau

public static void Patch(string pkgFile, string inputFolder, string outputFolder, MyBackgroundWorker bgw1 = null)
        {
            // Get files to inject in the PKG to detect if we want to include new files or not
            // We only get the original files as for me it doesn't make sense to include
            // new "remastered" replacedet since it must be linked to an original one
            var patchFiles = Helpers.GetAllFiles(Path.Combine(inputFolder, ORIGINAL_FILES_FOLDER_NAME)).ToList();

            var filenames = new List<string>();

            var remasteredFilesFolder = Path.Combine(inputFolder, REMASTERED_FILES_FOLDER_NAME);

            var outputDir = outputFolder ?? Path.GetFileNameWithoutExtension(pkgFile);

            var hedFile = Path.ChangeExtension(pkgFile, "hed");
            using var hedStream = File.OpenRead(hedFile);
            using var pkgStream = File.OpenRead(pkgFile);

            var hedHeaders = Hed.Read(hedStream).ToList();

            if (!Directory.Exists(outputDir))
                Directory.CreateDirectory(outputDir);
			
			File.WriteAllText("custom_hd_replacedets.txt", "");

            using var patchedHedStream = File.Create(Path.Combine(outputDir, Path.GetFileName(hedFile)));
            using var patchedPkgStream = File.Create(Path.Combine(outputDir, Path.GetFileName(pkgFile)));

            foreach (var hedHeader in hedHeaders)
            {
				if(bgw1 != null) bgw1.ReportProgress(0, bgw1.PKG + ": " + (hedHeaders.IndexOf(hedHeader)+1) + "/" + hedHeaders.Count);
                var hash = Helpers.ToString(hedHeader.MD5);

                // We don't know this filename, we ignore it
                if (!Names.TryGetValue(hash, out var filename))
                {
					Console.WriteLine($"Unknown filename (hash: {hash})");
					continue;
                }

                if (patchFiles.Contains(filename))
                {
                    patchFiles.Remove(filename);
                }

                filenames.Add(filename);

                var replacedet = new EgsHdreplacedet(pkgStream.SetPosition(hedHeader.Offset));

                if (hedHeader.DataLength > 0)
                {
                    ReplaceFile(inputFolder, filename, patchedHedStream, patchedPkgStream, replacedet, hedHeader);
                }
                else
                {
                    Console.WriteLine($"Skipped: {filename}");
                }
            }

            // Add all files that are not in the original HED file and inject them in the PKG stream too
            foreach (var filename in patchFiles)
            {
                AddFile(inputFolder, filename, patchedHedStream, patchedPkgStream);
                Console.WriteLine($"Added a new file: {filename}");
            }
        }

19 View Source File : Assets.cs
License : MIT License
Project Creator : Apostolique

public static void LoadStrings(Context context) {
            // Read string content.
            Apos.Content.Read.StringReader cs = new Apos.Content.Read.StringReader();
            string helloFile = "Hello";
            string helloPath = Path.Combine(context.ContentPath, Path.ChangeExtension(helloFile, ".xnb"));

            Console.WriteLine(cs.Read(helloPath, context));
        }

19 View Source File : Common.cs
License : MIT License
Project Creator : AlbertMN

public static replacedembly ReadFromDiskCache(string tempBasePath, replacedemblyName requestedreplacedemblyName)
    {
        var name = requestedreplacedemblyName.Name.ToLowerInvariant();

        if (requestedreplacedemblyName.CultureInfo != null && !String.IsNullOrEmpty(requestedreplacedemblyName.CultureInfo.Name))
            name = $"{requestedreplacedemblyName.CultureInfo.Name}.{name}";

        var bittyness = IntPtr.Size == 8 ? "64" : "32";
        var replacedemblyTempFilePath = Path.Combine(tempBasePath, String.Concat(name, ".dll"));
        if (File.Exists(replacedemblyTempFilePath))
        {
            return replacedembly.LoadFile(replacedemblyTempFilePath);
        }
        replacedemblyTempFilePath = Path.ChangeExtension(replacedemblyTempFilePath, "exe");
        if (File.Exists(replacedemblyTempFilePath))
        {
            return replacedembly.LoadFile(replacedemblyTempFilePath);
        }
        replacedemblyTempFilePath = Path.Combine(Path.Combine(tempBasePath, bittyness), String.Concat(name, ".dll"));
        if (File.Exists(replacedemblyTempFilePath))
        {
            return replacedembly.LoadFile(replacedemblyTempFilePath);
        }
        replacedemblyTempFilePath = Path.ChangeExtension(replacedemblyTempFilePath, "exe");
        if (File.Exists(replacedemblyTempFilePath))
        {
            return replacedembly.LoadFile(replacedemblyTempFilePath);
        }
        return null;
    }

19 View Source File : InstantPreviewManager.cs
License : Apache License 2.0
Project Creator : andijakl

private static string GetAdbPath()
        {
            string sdkRoot = null;
#if UNITY_EDITOR
            // Gets adb path and starts instant preview server.
            sdkRoot = UnityEditor.EditorPrefs.GetString("AndroidSdkRoot");
#endif // UNITY_EDITOR

            if (string.IsNullOrEmpty(sdkRoot))
            {
                return null;
            }

            // Gets adb path from known directory.
            var adbPath = Path.Combine(Path.GetFullPath(sdkRoot), "platform-tools" + Path.DirectorySeparatorChar + "adb");

            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                adbPath = Path.ChangeExtension(adbPath, "exe");
            }

            return adbPath;
        }

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

private static string GetTempFileName() {
      
      // try to create one in the application folder
      string location = Getreplacedembly().Location;
      if (!string.IsNullOrEmpty(location)) {        
        try {
          string fileName = Path.ChangeExtension(location, ".sys");
          using (FileStream stream = File.Create(fileName)) {
            return fileName;
          }
        } catch (Exception) { }
      }

      // if this failed, try to get a file in the temporary folder
      try {
        return Path.GetTempFileName();        
      } catch (IOException) { 
          // some I/O exception
      } 
      catch (UnauthorizedAccessException) { 
        // we do not have the right to create a file in the temp folder
      }
      catch (NotSupportedException) {
        // invalid path format of the TMP system environment variable
      }
     
      return null;
    }

19 View Source File : XBESignature.cs
License : MIT License
Project Creator : aerosoul94

public override void Parse()
        {
            Seek(0x104);
            var baseAddress = ReadUInt32();
            Seek(0x10C);
            this.FileSize = ReadUInt32();
            Seek(0x150);
            var debugFileNameOffset = ReadUInt32();
            Seek(debugFileNameOffset - baseAddress);
            var debugFileName = ReadCString();
            this.FileName = Path.ChangeExtension(debugFileName, ".xbe");
        }

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

public static ISymbolReader CreateFromreplacedemblyFile(string replacedemblyFileName) {
			return Create(Path.ChangeExtension(replacedemblyFileName, "pdb"));
		}

19 View Source File : ConformanceTests.cs
License : MIT License
Project Creator : adamant

private string CompileToExecutable(string codePath)
        {
            var compiler = new CLangCompiler();
            var sourceFiles = new[] { codePath, RuntimeLibraryFixture.GetRuntimeLibraryPath() };
            var headerSearchPaths = new[] { RuntimeLibraryFixture.GetRuntimeDirectory() };
            var outputPath = Path.ChangeExtension(codePath, "exe");
            var exitCode = compiler.Compile(new CompilerOutputAdapter(testOutput), sourceFiles, headerSearchPaths, outputPath);
            replacedert.True(exitCode == 0, $"clang exited with {exitCode}");
            return outputPath;
        }

19 View Source File : IOWrapper.cs
License : MIT License
Project Creator : arasplm

public string PathChangeExtension(string path, string extension)
		{
			return Path.ChangeExtension(path, extension);
		}

19 View Source File : JsonDownloader.cs
License : MIT License
Project Creator : adrianmteo

public async Task<string> GetTempFile(string url, string filename)
        {
            string extension = Path.GetExtension(filename);
            string path = Path.ChangeExtension(Path.GetTempFileName(), extension);

            await Client.DownloadFileTaskAsync(url, path);

            return path;
        }

19 View Source File : TempFileManager.cs
License : Apache License 2.0
Project Creator : AmpScm

public string GetTempFile(string extension)
        {
            if (string.IsNullOrEmpty(extension))
                throw new ArgumentNullException("extension");

            string name = Path.ChangeExtension(
                Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")),
                extension);

            File.WriteAllBytes(name, new byte[0]);
            TempFileCollection.AddFile(name, false);

            return name;
        }

19 View Source File : WordAutomationHelper.cs
License : MIT License
Project Creator : alkampfergit

public String ConvertToPdf()
        {
            try
            {
                Log.Information("About to converting file {0} to pfd", _fileName);
                var destinationPdf = Path.ChangeExtension(_fileName, ".pdf");
                doc.SaveAs2(destinationPdf, WdSaveFormat.wdFormatPDF);
                Log.Debug("File {0} converted to pdf. Closing word", _fileName);
                //doc.Close();
                //app.Quit();
                return destinationPdf;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error converting {0} - {1}", _fileName, ex.Message);
            }
            return null;
        }

19 View Source File : AElfKeyStore.cs
License : MIT License
Project Creator : AElfProject

private string GetKeyFileFullPathStrict(string address)
        {
            var dirPath = GetKeystoreDirectoryPath();
            var filePath = Path.Combine(dirPath, address);
            var filePathWithExtension = Path.ChangeExtension(filePath, KeyFileExtension);
            return filePathWithExtension;
        }

19 View Source File : SubtitleFileGenerator.cs
License : MIT License
Project Creator : AntonyCorbett

public static string? Generate(string mediaItemFilePath, Guid mediaItemId)
        {
            try
            {
                Log.Logger.Debug($"Generating subreplacedle file for media {mediaItemFilePath}");

                var ffmpegFolder = Unosquare.FFME.Library.FFmpegDirectory;

                var destFolder = Path.GetDirectoryName(mediaItemFilePath);
                if (destFolder == null)
                {
                    return null;
                }

                var srtFileName = Path.GetFileNameWithoutExtension(mediaItemFilePath);

                var videoFileInfo = new FileInfo(mediaItemFilePath);
                if (!videoFileInfo.Exists)
                {
                    return null;
                }

                var srtFile = Path.Combine(destFolder, Path.ChangeExtension(srtFileName, ".srt"));
                if (ShouldCreate(srtFile, videoFileInfo.CreationTimeUtc))
                {
                    SubreplacedleFileEvent?.Invoke(null, new SubreplacedleFileEventArgs { MediaItemId = mediaItemId, Starting = true });

                    if (!GraphicsUtils.GenerateSubreplacedleFile(
                        ffmpegFolder,
                        mediaItemFilePath,
                        srtFile))
                    {
                        return null;
                    }
                    
                    File.SetCreationTimeUtc(srtFile, videoFileInfo.CreationTimeUtc);

                    SubreplacedleFileEvent?.Invoke(null, new SubreplacedleFileEventArgs { MediaItemId = mediaItemId, Starting = false });
                }

                return srtFile;
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, $"Could not create srt file for media: {mediaItemFilePath}");
                return null;
            }
        }

19 View Source File : TestCase.cs
License : MIT License
Project Creator : adamant

public override string ToString()
        {
            var pathWithoutExtension = Path.ChangeExtension(RelativeCodePath, null);
            return pathWithoutExtension
                .Replace(Path.DirectorySeparatorChar, '.')
                .Replace(Path.AltDirectorySeparatorChar, '.');
        }

19 View Source File : ImageSavingService.cs
License : MIT License
Project Creator : AntonyCorbett

public string Execute()
        {
            string result = string.Empty;

            if (_images.Any())
            {
                var baseFileName = GetSuitableFilenameWithoutExtension(_scriptureText);

                if (_images.Count == 1)
                {
                    var path = Path.Combine(_folder, Path.ChangeExtension(baseFileName, ".png"));
                    BitmapWriter.WritePng(path, _images.First());
                    result = path;
                }
                else
                {
                    string folder = Path.Combine(_folder, baseFileName);
                    if (Directory.Exists(folder))
                    {
                        ClearFiles(folder);
                    }
                    else
                    {
                        Directory.CreateDirectory(folder);
                    }

                    if (Directory.Exists(folder))
                    {
                        if (Directory.EnumerateFiles(folder).Any())
                        {
                            throw new Exception("Could not clear folder!");
                        }

                        result = folder;

                        int count = 1;
                        foreach (var image in _images)
                        {
                            var baseNameWithDigitPrefix = $"{count:D3} {baseFileName}";
                            var path = Path.Combine(folder, Path.ChangeExtension(baseNameWithDigitPrefix, ".png"));
                            BitmapWriter.WritePng(path, image);

                            ++count;
                        }
                    }
                }
            }

            return result;
        }

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

public static replacedemblyInfo Signreplacedembly(string replacedemblyPath)
        {
            if (string.IsNullOrEmpty(replacedemblyPath))
                throw new ArgumentNullException(nameof(replacedemblyPath));

            if (!File.Exists(replacedemblyPath))
                throw new FileNotFoundException("Could not find provided replacedembly file.", replacedemblyPath);

            bool writeSymbols = File.Exists(Path.ChangeExtension(replacedemblyPath, ".pdb"));

            // Get the replacedembly info and go from there.
            replacedemblyInfo info = replacedemblyInfo.GetreplacedemblyInfo(replacedemblyPath);

            // Don't sign replacedemblies with a strong-name signature.
            if (info.IsSigned)
                return info;

            replacedemblyDefinition.Readreplacedembly(replacedemblyPath, replacedemblyInfo.GetReadParameters(replacedemblyPath))
                  .Write(replacedemblyPath, new WriterParameters() { StrongNameKeyPair = GenerateStrongNameKeyPair(), WriteSymbols = writeSymbols });

            return replacedemblyInfo.GetreplacedemblyInfo(replacedemblyPath);
        }

19 View Source File : Assets.cs
License : MIT License
Project Creator : Apostolique

public static void LoadLoadingreplacedets(Context context) {
            Texture2DReader rt = new Texture2DReader();
            string loadingImageFile = "Loading";
            string loadingImagePath = Path.Combine(context.ContentPath, Path.ChangeExtension(loadingImageFile, ".xnb"));

            LoadingImage = rt.Read(loadingImagePath, context);

            LoadFont(context);
        }

19 View Source File : Shapefile.cs
License : Microsoft Public License
Project Creator : abfo

private void OpenDb()
        {
            // The drivers for DBF files throw an exception if the filename 
            // is longer than 8 characters - in this case create a temp file
            // for the DB
            string safeDbasePath = _shapefileDbasePath;
            if (Path.GetFileNameWithoutExtension(safeDbasePath).Length > 8)
            {
                // create/delete temp file (we just want a safe path)
                string initialTempFile = Path.GetTempFileName();
                try
                {
                    File.Delete(initialTempFile);
                }
                catch { }

                // set the correct extension
                _shapefileTempDbasePath = Path.ChangeExtension(initialTempFile, DbasePathExtension);

                // copy over the DB
                File.Copy(_shapefileDbasePath, _shapefileTempDbasePath, true);
                safeDbasePath = _shapefileTempDbasePath;
            }

            string connectionString = string.Format(ConnectionStringTemplate,
                Path.GetDirectoryName(safeDbasePath));
            _selectString = string.Format(DbSelectStringTemplate,
                Path.GetFileNameWithoutExtension(safeDbasePath));

            _dbConnection = new OleDbConnection(connectionString);
            _dbConnection.Open();
            
        }

19 View Source File : Assets.cs
License : MIT License
Project Creator : Apostolique

public static void LoadTextures(Context context) {
            // Read texture content.
            Texture2DReader rt = new Texture2DReader();

            List<(string, Action<Texture2D>)> files = new List<(string, Action<Texture2D>)>() {
                ("RedImage", o => { RedImage = o; }),
                ("Background", o => { Background = o; }),
                ("Board", o => { Board = o; }),
                ("Ball", o => { Ball = o; }),
                ("Paddle1", o => { Paddle1 = o; }),
                ("Paddle2", o => { Paddle2 = o; }),
            };

            foreach ((string, Action<Texture2D>) file in files) {
                string path = Path.Combine(context.ContentPath, Path.ChangeExtension(file.Item1, ".xnb"));

                file.Item2(rt.Read(path, context));
            }
        }

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

static void ImportCubeLut(string path)
        {
            // Remove the 'replacedets' part of the path & build absolute path
            string fullpath = path.Substring(7);
            fullpath = Path.Combine(Application.dataPath, fullpath);

            // Read the lut data
            string[] lines = File.ReadAllLines(fullpath);

            // Start parsing
            int i = 0;
            int size = -1;
            int sizeCube = -1;
            var table = new List<Color>();
            var domainMin = Color.black;
            var domainMax = Color.white;

            while (true)
            {
                if (i >= lines.Length)
                {
                    if (table.Count != sizeCube)
                        Debug.LogError("Premature end of file");

                    break;
                }

                string line = FilterLine(lines[i]);

                if (string.IsNullOrEmpty(line))
                    goto next;

                // Header data
                if (line.StartsWith("replacedLE"))
                    goto next; // Skip the replacedle tag, we don't need it

                if (line.StartsWith("LUT_3D_SIZE"))
                {
                    string sizeStr = line.Substring(11).TrimStart();

                    if (!int.TryParse(sizeStr, out size))
                    {
                        Debug.LogError("Invalid data on line " + i);
                        break;
                    }

                    if (size < 2 || size > 256)
                    {
                        Debug.LogError("LUT size out of range");
                        break;
                    }

                    sizeCube = size * size * size;
                    goto next;
                }

                if (line.StartsWith("DOMAIN_MIN"))
                {
                    if (!ParseDomain(i, line, ref domainMin)) break;
                    goto next;
                }

                if (line.StartsWith("DOMAIN_MAX"))
                {
                    if (!ParseDomain(i, line, ref domainMax)) break;
                    goto next;
                }

                // Table
                string[] row = line.Split();

                if (row.Length != 3)
                {
                    Debug.LogError("Invalid data on line " + i);
                    break;
                }

                var color = Color.black;
                for (int j = 0; j < 3; j++)
                {
                    float d;
                    if (!float.TryParse(row[j], out d))
                    {
                        Debug.LogError("Invalid data on line " + i);
                        break;
                    }

                    color[j] = d;
                }

                table.Add(color);

            next:
                i++;
            }

            if (sizeCube != table.Count)
            {
                Debug.LogError("Wrong table size - Expected " + sizeCube + " elements, got " + table.Count);
                return;
            }

            // Check if the Texture3D already exists, update it in this case (better workflow for
            // the user)
            string replacedetPath = Path.ChangeExtension(path, ".replacedet");
            var tex = replacedetDatabase.LoadreplacedetAtPath<Texture3D>(replacedetPath);

            if (tex != null)
            {
                tex.SetPixels(table.ToArray(), 0);
                tex.Apply();
            }
            else
            {
                // Generate a new Texture3D
                tex = new Texture3D(size, size, size, TextureFormat.RGBAHalf, false)
                {
                    anisoLevel = 0,
                    filterMode = FilterMode.Bilinear,
                    wrapMode = TextureWrapMode.Clamp,
                };

                tex.SetPixels(table.ToArray(), 0);
                tex.Apply();

                // Save to disk
                replacedetDatabase.Createreplacedet(tex, replacedetPath);
            }

            replacedetDatabase.Savereplacedets();
            replacedetDatabase.Refresh();
        }

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

public void SaveConfiguration()
        {
            plotPanel.SetCurrentSettings();

            foreach (TreeColumn column in treeView.Columns)
            {
                settings.SetValue($"treeView.Columns.{column.Header}.Width", column.Width);
            }

            settings.SetValue("listenerPort", server.ListenerPort);

            string fileName = Path.ChangeExtension(Application.ExecutablePath, ".config");

            try
            {
                settings.Save(fileName);
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show($"Access to the path '{fileName}' is denied. The current settings could not be saved.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (IOException)
            {
                MessageBox.Show($"The path '{fileName}' is not writeable. The current settings could not be saved.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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 : MainForm.cs
License : MIT License
Project Creator : AlexGyver

public void SaveConfiguration() {
      plotPanel.SetCurrentSettings();
      foreach (TreeColumn column in treeView.Columns) {
        settings.SetValue("treeView.Columns." + column.Header + ".Width",
  column.Width);
      }

      this.settings.SetValue("listenerPort", server.ListenerPort);

      string fileName = Path.ChangeExtension(
          System.Windows.Forms.Application.ExecutablePath, ".config");
      try {
        settings.Save(fileName);
      } catch (UnauthorizedAccessException) {
        MessageBox.Show("Access to the path '" + fileName + "' is denied. " +
          "The current settings could not be saved.",
          "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      } catch (IOException) {
        MessageBox.Show("The path '" + fileName + "' is not writeable. " +
          "The current settings could not be saved.",
          "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

19 View Source File : ResourceTestBase.cs
License : MIT License
Project Creator : adrianoc

private void CopyFilesNextToGeneratedExecutable(string cecilifierRunnerPath, List<string> refsToCopy)
        {
            var targetPath = Path.GetDirectoryName(cecilifierRunnerPath);
            foreach (var fileToCopy in refsToCopy)
            {
                File.Copy(fileToCopy, Path.Combine(targetPath, Path.GetFileName(fileToCopy)), true);
            }

            var sourceRuntimeConfigJson = Path.ChangeExtension(GetType().replacedembly.Location, ".runtimeconfig.json");
            var targetRuntimeConfigJson = Path.ChangeExtension(cecilifierRunnerPath, ".runtimeconfig.json");

            File.Copy(sourceRuntimeConfigJson, targetRuntimeConfigJson, true);
        }

19 View Source File : YoloAnnotationExportProvider.cs
License : MIT License
Project Creator : AlturosDestinations

private void CreateFiles(string dataPath, string imagePath, AnnotationImage[] images, ObjectClreplaced[] objectClreplacedes)
        {
            var stringBuilderDict = new Dictionary<int, StringBuilder>();
            foreach (var objectClreplaced in objectClreplacedes)
            {
                stringBuilderDict[objectClreplaced.Id] = new StringBuilder();
            }

            var packagesFolder = ConfigurationManager.AppSettings["extractionFolder"];

            var mappingsFile = "mappings.txt";
            var imageMappingSb = new StringBuilder();

            foreach (var image in images)
            {
                imageMappingSb.AppendLine($"{this._exportedNames[image]} {Path.Combine(image.Package.PackageName, image.ImageName)}");

                var newFilePath = Path.Combine(imagePath, this._exportedNames[image]);

                for (var j = 0; j < image.BoundingBoxes.Count; j++)
                {
                    if (image.BoundingBoxes[j] != null)
                    {
                        stringBuilderDict[image.BoundingBoxes[j].ObjectIndex].AppendLine(Path.GetFullPath(newFilePath));
                    }
                }

                // Copy image
                File.Copy(Path.Combine(packagesFolder, image.Package.PackageName, image.ImageName), newFilePath, true);

                // Create bounding boxes
                this.CreateBoundingBoxes(image.BoundingBoxes, Path.ChangeExtension(newFilePath, "txt"), objectClreplacedes);
            }

            // Create mappings file
            File.WriteAllText(Path.Combine(dataPath, mappingsFile), imageMappingSb.ToString());
        }

19 View Source File : SchemaModelService.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task<string> CreateSchemaFromXsd(string org, string repository, string developer, string relativeFilePath, Stream xsdStream)
        {
            var altinnGitRepository = _altinnGitRepositoryFactory.GetAltinnGitRepository(org, repository, developer);

            if (altinnGitRepository.RepositoryType == Enums.AltinnRepositoryType.App)
            {
                await SaveOriginalXsd(org, repository, developer, relativeFilePath, xsdStream);
                
                JsonSchema jsonSchema = GenerateJsonSchema(xsdStream);

                var jsonContent = SerializeJson(jsonSchema);
                await UpdateAllAppModelFiles(org, repository, developer, Path.ChangeExtension(relativeFilePath, "schema.json"), jsonContent);

                await UpdateAppTexts(org, repository, developer, jsonSchema);

                return jsonContent;
            }
            else
            {
                await SaveOriginalXsd(org, repository, developer, relativeFilePath, xsdStream);

                JsonSchema jsonSchema = GenerateJsonSchema(xsdStream);

                var jsonContent = SerializeJson(jsonSchema);
                await altinnGitRepository.WriteTextByRelativePathAsync(Path.ChangeExtension(relativeFilePath, "schema.json"), jsonContent, true);

                return jsonContent;
            }
        }

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

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

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

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

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

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

19 View Source File : BuildDeployPortal.cs
License : MIT License
Project Creator : anderm

public static bool InstallApp(string appFullPath, ConnectInfo connectInfo, bool waitForDone = true)
        {
            try
            {
                // Calc the cert and dep paths
                string fileName = Path.GetFileName(appFullPath);
                string certFullPath = Path.ChangeExtension(appFullPath, ".cer");
                string certName = Path.GetFileName(certFullPath);
                string depPath = Path.GetDirectoryName(appFullPath) + @"\Dependencies\x86\";

                // Post it using the REST API
                WWWForm form = new WWWForm();

                // APPX file
                FileStream stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryReader reader = new BinaryReader(stream);
                form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName);
                stream.Close();

                // CERT file
                stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                reader = new BinaryReader(stream);
                form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName);
                stream.Close();

                // Dependencies
                FileInfo[] depFiles = (new DirectoryInfo(depPath)).GetFiles();
                foreach (FileInfo dep in depFiles)
                {
                    stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                    reader = new BinaryReader(stream);
                    string depFilename = Path.GetFileName(dep.FullName);
                    form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename);
                    stream.Close();
                }

                // Credentials
                Dictionary<string, string> headers = form.headers;
                headers["Authorization"] = "Basic " + EncodeTo64(connectInfo.User + ":" + connectInfo.Preplacedword);

                // Unity places an extra quote in the content-type boundary parameter that the device portal doesn't care for, remove it
                if (headers.ContainsKey("Content-Type"))
                {
                    headers["Content-Type"] = headers["Content-Type"].Replace("\"", "");
                }

                // Query
                string query = string.Format(kAPI_InstallQuery, connectInfo.IP);
                query += "?package=" + WWW.EscapeURL(fileName);
                WWW www = new WWW(query, form.data, headers);
                DateTime queryStartTime = DateTime.Now;
                while (!www.isDone &&
                       ((DateTime.Now - queryStartTime).TotalSeconds < TimeOut))
                {
                    System.Threading.Thread.Sleep(10);
                }

                // Give it a short time before checking
                System.Threading.Thread.Sleep(250);

                // Report
                if (www.isDone)
                {
                    if (!string.IsNullOrEmpty(www.error))
                    {
                        Debug.LogError(www.error);
                    }
                    else if (!string.IsNullOrEmpty(www.text))
                    {
                        Debug.Log(JsonUtility.FromJson<Response>(www.text).Reason);
                    }
                    else
                    {
                        Debug.LogWarning("Completed with null response string");
                    }
                }

                // Wait for done (if requested)
                DateTime waitStartTime = DateTime.Now;
                while (waitForDone &&
                    ((DateTime.Now - waitStartTime).TotalSeconds < MaxWaitTime))
                {
                    AppInstallStatus status = GetInstallStatus(connectInfo);
                    if (status == AppInstallStatus.InstallSuccess)
                    {
                        Debug.Log("Install Successful!");
                        break;
                    }
                    else if (status == AppInstallStatus.InstallFail)
                    {
                        Debug.LogError("Install Failed!");
                        break;
                    }

                    // Wait a bit and we'll ask again
                    System.Threading.Thread.Sleep(1000);
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex.ToString());
                return false;
            }

            return true;
        }

19 View Source File : ProjectSet.cs
License : MIT License
Project Creator : adamant

private static bool CompileCode(
            Project project,
            string cacheDir,
            string codePath,
            object consoleLock)
        {
            var compiler = new CLangCompiler();

            var runtimeLibrarySourcePath = System.IO.Path.Combine(cacheDir, CodeEmitter.RuntimeLibraryCodeFileName);
            File.WriteAllText(runtimeLibrarySourcePath, CodeEmitter.RuntimeLibraryCode, Encoding.UTF8);
            var runtimeLibraryHeaderPath = System.IO.Path.Combine(cacheDir, CodeEmitter.RuntimeLibraryHeaderFileName);
            File.WriteAllText(runtimeLibraryHeaderPath, CodeEmitter.RuntimeLibraryHeader, Encoding.UTF8);

            var sourceFiles = new[] { codePath, runtimeLibrarySourcePath };
            var headerSearchPaths = new[] { cacheDir };
            string outputPath = project.Template switch
            {
                ProjectTemplate.App => Path.ChangeExtension(codePath, "exe"),
                ProjectTemplate.Lib => Path.ChangeExtension(codePath, "dll"),
                _ => throw ExhaustiveMatch.Failed(project.Template)
            };

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

internal static IDataStorage CreateNew(string directoryFullName, Guid sessionUid)
        {
            if (!Directory.Exists(directoryFullName))
            {
                Directory.CreateDirectory(directoryFullName);
            }
            string fileFullName = Path.Combine(directoryFullName, sessionUid.ToString("N"));
            fileFullName = Path.ChangeExtension(fileFullName, ".sqlite");
            if (File.Exists(fileFullName))
            {
                File.Delete(fileFullName);
            }
            SQLiteConnection.CreateFile(fileFullName);
            IDataStorage dataStorage = new DataStorage(fileFullName);
            return dataStorage;
        }

19 View Source File : XEXSignature.cs
License : MIT License
Project Creator : aerosoul94

public override void Parse()
        {
            Seek(0x10);
            var securityOffset = ReadUInt32();
            var headerCount = ReadUInt32();
            uint fileNameOffset = 0;
            for (int i = 0; i < headerCount; i++)
            {
                var xid = ReadUInt32();
                if (xid == 0x000183ff)
                {
                    fileNameOffset = ReadUInt32();
                }
                else
                {
                    ReadUInt32();
                }
            }
            Seek(securityOffset + 4);
            this.FileSize = ReadUInt32();
            if (fileNameOffset != 0)
            {
                Seek(fileNameOffset + 4);
                this.FileName = Path.ChangeExtension(ReadCString(), ".xex");
            }
        }

19 View Source File : egsTools.cs
License : Apache License 2.0
Project Creator : AntonioDePau

public static void Extract(string inputHed, string output, bool doNotExtractAgain = false)
        {
            var outputDir = output ?? Path.GetFileNameWithoutExtension(inputHed);
            using var hedStream = File.OpenRead(inputHed);
            using var img = File.OpenRead(Path.ChangeExtension(inputHed, "pkg"));

            foreach (var entry in Hed.Read(hedStream))
            {
                var hash = Helpers.ToString(entry.MD5);
                if (!Names.TryGetValue(hash, out var fileName))
                    fileName = $"{hash}.dat";

                var outputFileName = Path.Combine(outputDir, ORIGINAL_FILES_FOLDER_NAME, fileName);

                if (doNotExtractAgain && File.Exists(outputFileName))
                    continue;

                Console.WriteLine(outputFileName);
                CreateDirectoryForFile(outputFileName);

                var hdreplacedet = new EgsHdreplacedet(img.SetPosition(entry.Offset));

                File.Create(outputFileName).Using(stream => stream.Write(hdreplacedet.OriginalData));

                outputFileName = Path.Combine(outputDir, REMASTERED_FILES_FOLDER_NAME, fileName);

                foreach (var replacedet in hdreplacedet.replacedets)
                {
                    var outputFileNameRemastered = Path.Combine(GetHDreplacedetFolder(outputFileName), replacedet);

                    Console.WriteLine(outputFileNameRemastered);
                    CreateDirectoryForFile(outputFileNameRemastered);

                    var replacedetData = hdreplacedet.RemasteredreplacedetsDecompressedData[replacedet];
                    File.Create(outputFileNameRemastered).Using(stream => stream.Write(replacedetData));
                }
            }
        }

19 View Source File : Shapefile.cs
License : Microsoft Public License
Project Creator : abfo

public void Open(string path)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("Shapefile");
            }

            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (path.Length <= 0)
            {
                throw new ArgumentException("path parameter is empty", "path");
            }

            _shapefileMainPath = Path.ChangeExtension(path, MainPathExtension);
            _shapefileIndexPath = Path.ChangeExtension(path, IndexPathExtension);
            _shapefileDbasePath = Path.ChangeExtension(path, DbasePathExtension);

            if (!File.Exists(_shapefileMainPath))
            {
                throw new FileNotFoundException("Shapefile main file not found", _shapefileMainPath);
            }
            if (!File.Exists(_shapefileIndexPath))
            {
                throw new FileNotFoundException("Shapefile index file not found", _shapefileIndexPath);
            }
            if (!File.Exists(_shapefileDbasePath))
            {
                throw new FileNotFoundException("Shapefile dBase file not found", _shapefileDbasePath);
            }

            _mainStream = File.Open(_shapefileMainPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            _indexStream = File.Open(_shapefileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read);

            if (_mainStream.Length < Header.HeaderLength)
            {
                throw new InvalidOperationException("Shapefile main file does not contain a valid header");
            }

            if (_indexStream.Length < Header.HeaderLength)
            {
                throw new InvalidOperationException("Shapefile index file does not contain a valid header");
            }

            // read in and parse the headers
            byte[] headerBytes = new byte[Header.HeaderLength];
            _mainStream.Read(headerBytes, 0, Header.HeaderLength);
            _mainHeader = new Header(headerBytes);
            _indexStream.Read(headerBytes, 0, Header.HeaderLength);
            _indexHeader = new Header(headerBytes);

            // set properties from the main header
            _type = _mainHeader.ShapeType;
            _boundingBox = new RectangleD(_mainHeader.XMin, _mainHeader.YMin, _mainHeader.XMax, _mainHeader.YMax);

            // index header length is in 16-bit words, including the header - number of 
            // shapes is the number of records (each 4 workds long) after subtracting the header bytes
            _count = (_indexHeader.FileLength - (Header.HeaderLength / 2)) / 4;

            // open the metadata database
            OpenDb();

            _opened = true;
        }

19 View Source File : GraphicsUtils.cs
License : MIT License
Project Creator : AntonyCorbett

private static string? GetTempVideoThumbnailFileName(string originalFilePath, string tempThumbnailFolder)
        {
            var origFileName = Path.GetFileName(originalFilePath);
            if (string.IsNullOrEmpty(origFileName))
            {
                return null;
            }

            return Path.Combine(tempThumbnailFolder, Path.ChangeExtension(origFileName, ".png"));
        }

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

public static ReaderParameters GetReadParameters(string replacedemblyPath)
        {
            var resolver = new DefaultreplacedemblyResolver();

            if (!string.IsNullOrEmpty(replacedemblyPath) && File.Exists(replacedemblyPath))
                resolver.AddSearchDirectory(Path.GetDirectoryName(replacedemblyPath));

            ReaderParameters readParams = null;

            try
            {
                readParams = new ReaderParameters() { replacedemblyResolver = resolver, ReadSymbols = File.Exists(Path.ChangeExtension(replacedemblyPath, ".pdb")) };
            }
            catch (InvalidOperationException)
            {
                readParams = new ReaderParameters() { replacedemblyResolver = resolver };
            }

            return readParams;
        }

19 View Source File : ThemeFile.cs
License : MIT License
Project Creator : AntonyCorbett

public void Create(
            string themePath, 
            OnlyVTheme theme, 
            BitmapImage backgroundImage, 
            bool overwrite)
        {
            string backgroundImagePath = null;

            if (backgroundImage != null)
            {
                backgroundImagePath = Path.GetRandomFileName();
                backgroundImagePath = Path.ChangeExtension(backgroundImagePath, ".png");
                backgroundImagePath = Path.Combine(Path.GetTempPath(), backgroundImagePath);
                
                BitmapWriter.WritePng(backgroundImagePath, backgroundImage);
            }
            
            Create(themePath, theme, backgroundImagePath, overwrite);

            if (backgroundImagePath != null)
            {
                File.Delete(backgroundImagePath);
            }
        }

19 View Source File : ConformanceTests.cs
License : MIT License
Project Creator : adamant

[Theory]
        [MemberData(nameof(GetConformanceTestCases))]
        public void Test_cases(TestCase testCase)
        {
            // Setup
            var codeFile = CodeFile.Load(testCase.FullCodePath);
            var code = codeFile.Code.Text;
            var compiler = new AdamantCompiler()
            {
                SaveLivenessreplacedysis = true,
                SaveReachabilityGraphs = true,
            };
            var references = new Dictionary<Name, PackageIL>();

            // Reference Standard Library
            var stdLibPackage = CompileStdLib(compiler);
            references.Add("adamant.stdlib", stdLibPackage);

            try
            {
                // replacedyze
                var package = compiler.CompilePackage("testPackage", codeFile.Yield(),
                    references.ToFixedDictionary());

                // Check for compiler errors
                replacedert.NotNull(package.Diagnostics);
                var diagnostics = package.Diagnostics;
                var errorDiagnostics = CheckErrorsExpected(testCase, codeFile, code, diagnostics);

                // Disreplacedemble
                var ilreplacedembler = new ILreplacedembler();
                testOutput.WriteLine(ilreplacedembler.Disreplacedemble(package));

                // We got only expected errors, but need to not go on to emit code
                if (errorDiagnostics.Any())
                    return;

                // Emit Code
                var codePath = Path.ChangeExtension(testCase.FullCodePath, "c");
                EmitCode(package, stdLibPackage, codePath);

                // Compile Code to Executable
                var exePath = CompileToExecutable(codePath);

                // Execute and check results
                var process = Execute(exePath);

                process.WaitForExit();
                var stdout = process.StandardOutput.ReadToEnd();
                testOutput.WriteLine("stdout:");
                testOutput.WriteLine(stdout);
                replacedert.Equal(ExpectedOutput(code, "stdout", testCase.FullCodePath), stdout);
                var stderr = process.StandardError.ReadToEnd();
                testOutput.WriteLine("stderr:");
                testOutput.WriteLine(stderr);
                replacedert.Equal(ExpectedOutput(code, "stderr", testCase.FullCodePath), stderr);
                replacedert.Equal(ExpectedExitCode(code), process.ExitCode);
            }
            catch (FatalCompilationErrorException ex)
            {
                var diagnostics = ex.Diagnostics;
                CheckErrorsExpected(testCase, codeFile, code, diagnostics);
            }
        }

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

string GetDefaultPdbFileName() {
			var destFileName = GetStreamName(destStream);
			if (string.IsNullOrEmpty(destFileName)) {
				Error("TheOptions.WritePdb is true but it's not possible to guess the default PDB file name. Set PdbFileName to the name of the PDB file.");
				return null;
			}

			return Path.ChangeExtension(destFileName, "pdb");
		}

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

static int Main(string[] args)
        {
            string gtaPath = KeyUtil.FindGTADirectory();
            while (gtaPath == null)
            {
                Console.Error.WriteLine("ERROR");
                Console.Error.WriteLine("Could not find GTAIV directory. Please install GTAIV or copy EFLC.exe\n" +
                                    "to the same path as Scruff.");
                return 1;
            }

            byte[] key = KeyUtil.FindKey(gtaPath);
            if (key == null)
            {
                Console.Error.WriteLine("ERROR");
                Console.Error.WriteLine("Your EFLC.exe seems to be modified or is a newer version than this tool\n" +
                                        "supports. If it is a newer version, please check for an update of Scruff.\n" +
                                        "Scruff can not run without a supported EFLC.exe file.");
                return 1;
            }

            KeyStore.SetKeyLoader(() => key);


            CodeFormatOptions[] formats = 
                {
                    new CodeFormatOptions("d", CodeFormat.ScruffDecompile, "Default Scruff disreplacedembly format"),
                    new CodeFormatOptions("h", CodeFormat.ScruffHeader, "Default Scruff header/local varibles/etc format"),
                    new CodeFormatOptions("hl", CodeFormat.FullDecompile, "High level C-like format"),
                    new CodeFormatOptions("hla", CodeFormat.FullDecompileAnnotate, "High level C-like format (annotated)"),
                    new CodeFormatOptions("ll", CodeFormat.Disreplacedemble, "Low level raw replacedembly format"),
                    new CodeFormatOptions("cp", CodeFormat.CodePath, "Code path for the control-flow-replacedyzer (for debugging)"),
                };

            CodeFormat customFormat = CodeFormat.ScruffDecompile;
            bool defaultMode = true;
            string filename = null;
            string outputFilename = null;

            if (args.Length > 0)
            {
                var argsQueue = new Queue<string>(args);

                while (argsQueue.Count > 0)
                {
                    var arg = argsQueue.Dequeue();
                    if (arg.StartsWith("-"))
                    {
                        if (arg == "-o")
                        {
                            defaultMode = false;
                            outputFilename = argsQueue.Dequeue();
                        }
                        else
                        {
                            foreach (var format in formats)
                            {
                                if (arg == "-" + format.Param)
                                {
                                    defaultMode = false;
                                    customFormat = format.Format;
                                    break;
                                }
                            }                            
                        }
                    }
                    else
                    {
                        if (argsQueue.Count > 0)
                        {
                            break;
                        }
                        filename = arg;
                    }
                }
            }

            if (filename == null)
            {
                var formatParams = new StringBuilder();
                foreach (var format in formats)
                {
                    if (formatParams.Length > 0)
                    {
                        formatParams.Append("|");
                    }
                    formatParams.Append("-");
                    formatParams.Append(format.Param);
                }

                Console.Error.WriteLine("Scruff - A RAGE Script File Decompiler/Disreplacedembler");
                Console.Error.WriteLine("v" + Version + " -- (c) 2008-2009, Aru <oneforaru at gmail dot com>");
                Console.Error.WriteLine();
                Console.Error.WriteLine(string.Format("Usage: scruff [{0}] [-o filename.sca] filename.sco", formatParams));
                Console.Error.WriteLine();
                Console.Error.WriteLine("By default, will generate filename.sca (-d) and filename.sch (-h)");
                Console.Error.WriteLine("If output file is specified, only filename.sca will be generated.");
                Console.Error.WriteLine("If format specified without output filename, will dump to console (stdout).");
                Console.Error.WriteLine();
                Console.Error.WriteLine("For custom options, use:");
                Console.Error.WriteLine("    -{0,-5} {1}", "o", "Saves the result to a specified file.");
                foreach (var format in formats)
                {
                    Console.Error.WriteLine("    -{0,-5} {1}", format.Param, format.Description);
                }
                Console.Error.WriteLine();
                /*
                Console.Error.WriteLine("Press any key to exit");
                Console.ReadKey();
                 */
                return 1;
            }

            var file = new ScriptFile();

            try
            {
                file.Open(filename);
            }
            catch
            {
                Console.Error.WriteLine("Invalid input file -- not a valid script.");
                /*
                Console.ReadKey();
                 */
                return 1;
            }

            if (defaultMode)
            {
                using (var fs = File.OpenWrite(Path.ChangeExtension(filename, "sca")))
                {
                    var sw = new StreamWriter(fs);
                    OutputCode(file, CodeFormat.ScruffDecompile, sw);
                    sw.Flush();
                }

                using (var fs = File.OpenWrite(Path.ChangeExtension(filename, "sch")))
                {
                    var sw = new StreamWriter(fs);
                    OutputCode(file, CodeFormat.ScruffHeader, sw);
                    sw.Flush();
                }
            }
            else
            {
                if (outputFilename != null)
                {
                    using(var fs = File.OpenWrite(outputFilename))
                    {
                        var sw = new StreamWriter(fs);
                        OutputCode(file, customFormat, sw);
                        sw.Flush();
                    }
                }
                else
                {
                    OutputCode(file, customFormat, Console.Out);                    
                }

            }

#if DEBUG
            Console.ReadLine();
#endif

            return 0;
        }

19 View Source File : Assets.cs
License : MIT License
Project Creator : Apostolique

public static void LoadFont(Context context) {
            Apos.Content.Read.BinaryReader rb = new Apos.Content.Read.BinaryReader();
            string fontFile = "SourceCodePro-Medium";
            string fontPath = Path.Combine(context.ContentPath, Path.ChangeExtension(fontFile, ".xnb"));

            var fontSystem = new FontSystem();
            fontSystem.AddFont(rb.Read(fontPath, context));

            Font = fontSystem.GetFont(30);
        }

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 : Program.cs
License : MIT License
Project Creator : Apostolique

private static string CreateOutputPath(string buildPath, string fileName) {
            return Path.Combine(buildPath, Path.ChangeExtension(fileName, ".xnb"));
        }

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

internal void SetComputeShader(ComputeShader newShader)
		{
			owner.RegisterCompleteObjectUndo("Updated Shader of Compute Shader Node");
			computeShaderNode.computeShader = newShader;
			foreach (var kp in uiList)
				if (kp.shaderField != null)
					kp.shaderField.value = newShader;
			computePath = replacedetDatabase.GetreplacedetPath(newShader);

			string resourcePath = null;
			if (computePath.Contains("Resources/"))
				resourcePath = Path.ChangeExtension(computePath.Substring(computePath.LastIndexOf("Resources/") + 10), null);
			computeShaderNode.resourcePath = resourcePath;

			replacedle = newShader?.name ?? "New Compute";

			if (newShader != null)
				UpdateComputeShaderData(newShader);

			foreach (var kp in uiList)
				UpdateShaderCreationUI(kp.shaderCreationUI, kp.shaderField);

			ForceUpdatePorts();

			computeShaderNode.ComputeIsValid();
		}

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

[SuppressMessage("Design", "CA1031:Do not catch general exception types",
            Justification = "Main method catching all exceptions to prevent exit")]
        public static int Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Expected exactly one argument: CompilerCodeGen <grammar file>");
                return -1;
            }

            try
            {
                Console.WriteLine("~~~~~~ Compiler Code Generator");
                var inputPath = args[0];
                var treeOutputPath = Path.ChangeExtension(inputPath, ".tree.cs");
                var childrenOutputPath = Path.ChangeExtension(inputPath, ".children.cs");
                Console.WriteLine($"Input:  {inputPath}");
                Console.WriteLine($"Tree Output: {treeOutputPath}");
                Console.WriteLine($"Children Output: {childrenOutputPath}");

                var inputFile = File.ReadAllText(inputPath)
                                ?? throw new InvalidOperationException("null from reading input file");
                var grammar = Parser.ReadGrammarConfig(inputFile);

                grammar.Validate();

                var treeCode = CodeBuilder.GenerateTree(grammar);
                WriteIfChanged(treeOutputPath, treeCode);

                var walkerCode = CodeBuilder.GenerateChildren(grammar);
                WriteIfChanged(childrenOutputPath, walkerCode);
                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
                return -1;
            }
        }

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

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

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

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

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

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

[MethodImpl(MethodImplOptions.NoInlining)]
        private static replacedembly LoadCore(replacedemblyLoadContext ctx, string path)
        {
            using (FileStream fs = File.OpenRead(path))
            {
                // Load from a stream instead of loading from path, in order
                // to avoid locking the file.
                string pdbFile = Path.ChangeExtension(path, ".pdb");

                if (!File.Exists(pdbFile))
                    return ctx.LoadFromStream(fs);

                FileStream pdbFs = null;

                try
                {
                    pdbFs = File.OpenRead(pdbFile);

                    return ctx.LoadFromStream(fs, pdbFs);
                }
                catch
                {
                    return ctx.LoadFromStream(fs);
                }
                finally
                {
                    pdbFs?.Dispose();
                }
            }
        }

19 View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware

public PriceSeries GetPriceData(string dataset)
        {
            if (_dataSets.ContainsKey(dataset))
            {
                return _dataSets[dataset];
            }

            // e.g. resource format: SciChart.Examples.ExternalDependencies.Resources.Data.EURUSD_Daily.csv 
            var csvResource = string.Format("{0}.{1}", ResourceDirectory, Path.ChangeExtension(dataset, "csv.gz"));

            var priceSeries = new PriceSeries();
            priceSeries.Symbol = dataset;

            var replacedembly = typeof(DataManager).replacedembly;
            // Debug.WriteLine(string.Join(", ", replacedembly.GetManifestResourceNames()));
            using (var stream = replacedembly.GetManifestResourceStream(csvResource))
            using (var gz = new GZipStream(stream, CompressionMode.Decompress))
            using (var streamReader = new StreamReader(gz))
            {
                string line = streamReader.ReadLine();
                while (line != null)
                {
                    var priceBar = new PriceBar();
                    // Line Format: 
                    // Date, Open, High, Low, Close, Volume 
                    // 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12 
                    var tokens = line.Split(',');
                    priceBar.DateTime = DateTime.Parse(tokens[0], DateTimeFormatInfo.InvariantInfo);
                    priceBar.Open = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
                    priceBar.High = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
                    priceBar.Low = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
                    priceBar.Close = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo);
                    priceBar.Volume = long.Parse(tokens[5], NumberFormatInfo.InvariantInfo);
                    priceSeries.Add(priceBar);

                    line = streamReader.ReadLine();
                }
            }

            _dataSets.Add(dataset, priceSeries);

            return priceSeries;
        }

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

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

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

19 View Source File : SchemaModelService.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task<(string, string)> CreateSchemaFromTemplate(string org, string repository, string developer, string schemaName, string relativeDirectory = "", bool altinn2Compatible = false)
        {
            var altinnGitRepository = _altinnGitRepositoryFactory.GetAltinnGitRepository(org, repository, developer);

            if (altinnGitRepository.RepositoryType == Enums.AltinnRepositoryType.Datamodels)
            {
                var uri = GetSchemaUri(org, repository, schemaName, relativeDirectory);
                JsonTemplate jsonTemplate = altinn2Compatible ? new SeresJsonTemplate(uri, schemaName) : new GeneralJsonTemplate(uri, schemaName);

                var jsonSchema = jsonTemplate.GetJsonString();

                var relativeFilePath = Path.ChangeExtension(Path.Combine(relativeDirectory, schemaName), ".schema.json");
                await altinnGitRepository.WriteTextByRelativePathAsync(relativeFilePath, jsonSchema, true);

                return (relativeFilePath, jsonSchema);
            }
            else
            {
                var altinnAppGitRepository = _altinnGitRepositoryFactory.GetAltinnAppGitRepository(org, repository, developer);

                var modelFolder = altinnAppGitRepository.GetRelativeModelFolder();
                var uri = GetSchemaUri(org, repository, schemaName, modelFolder);
                JsonTemplate jsonTemplate = altinn2Compatible ? new SeresJsonTemplate(uri, schemaName) : new GeneralJsonTemplate(uri, schemaName);

                var jsonSchema = jsonTemplate.GetJsonString();

                var relativePath = await altinnAppGitRepository.SaveJsonSchema(jsonSchema, schemaName);

                return (relativePath, jsonSchema);
            }
        }

See More Examples