System.IO.Path.GetTempPath()

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

1972 Examples 7

19 Source : PulseLogPrivesc.cs
with Apache License 2.0
from AlmondOffSec

private static bool CreateMountPoint(string path, out string redirectedPath)
        {
            redirectedPath = null;
            try
            {
                DirectoryInfo to = Directory.GetParent(path);
                string filename = Path.GetFileName(path);
                if(to == null)
                    return false;
                DirectoryInfo from = Directory.CreateDirectory(Path.GetTempPath() + System.Guid.NewGuid().ToString());
                if(from == null)
                    return false;
                Log("Creating mount point: " + from.FullName + " -> " + to.FullName);
                NtFile.CreateMountPoint("\\??\\" + from.FullName, "\\??\\" + to.FullName, null);
                redirectedPath = Path.Combine(from.FullName, filename);
                Log("Target path is now " + redirectedPath);
            } catch {
                return false;
            }
            return true;
        }

19 Source : FileSystemResultsWriter.cs
with Apache License 2.0
from allure-framework

private string GetResultsDirectory(string outputDirectory)
    {
      var parentDir = new DirectoryInfo(outputDirectory).Parent.FullName;
      outputDirectory = HasDirectoryAccess(parentDir)
          ? outputDirectory
          : Path.Combine(
              Path.GetTempPath(), AllureConstants.DEFAULT_RESULTS_FOLDER);

      Directory.CreateDirectory(outputDirectory);

      return new DirectoryInfo(outputDirectory).FullName;
    }

19 Source : ApiClient.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public object Deserialize(IRestResponse response, Type type)
        {
            var headers = response.Headers;

            // return byte array
            if (type == typeof(byte[]))
            {
                return response.RawBytes;
            }

            // TODO: ? if (type.IsreplacedignableFrom(typeof(Stream)))
            if (type == typeof(Stream))
            {
                if (headers != null)
                {
                    var filePath = string.IsNullOrEmpty(Configuration.TempFolderPath)
                        ? Path.GetTempPath()
                        : Configuration.TempFolderPath;
                    var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
                    foreach (var header in headers)
                    {
                        var match = regex.Match(header.ToString());
                        if (match.Success)
                        {
                            string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", string.Empty).Replace("'", string.Empty));
                            File.WriteAllBytes(fileName, response.RawBytes);
                            return new FileStream(fileName, FileMode.Open);
                        }
                    }
                }

                var stream = new MemoryStream(response.RawBytes);
                return stream;
            }

            // return a datetime object
            if (type.Name.StartsWith("System.Nullable`1[[System.DateTime"))
            {
                return DateTime.Parse(response.Content,  null, System.Globalization.DateTimeStyles.RoundtripKind);
            }

            // return primitive type
            if (type == typeof(string) || type.Name.StartsWith("System.Nullable"))
            {
                return ConvertType(response.Content, type);
            }

            // at this point, it must be a model (json)
            try
            {
                return JsonConvert.DeserializeObject(response.Content, type, serializerSettings);
            }
            catch (Exception e)
            {
                throw new ApiException(500, e.Message);
            }
        }

19 Source : JoplinExportService.cs
with GNU General Public License v3.0
from alxnbl

private void ExportSection(Node section, string pageNameFilter = "")
        {
            var sectionMdFileContent = AddJoplinNodeMetadata(section, "");
            var notebookFolder = section.GetNotebookPath();

            string onExportFolder;
            
            if(_appSettings.UserTempFolder)
            {
                onExportFolder = Path.GetTempPath();
            }
            else 
            {
                onExportFolder = Path.Combine("tmp", notebookFolder);
                Directory.CreateDirectory(onExportFolder);
            }

            // Write Section Md File
            File.WriteAllText(Path.Combine(notebookFolder, $"{section.Id}.md"), sectionMdFileContent);

            if (section is Section sectionNode && !sectionNode.IsSectionGroup)
            {
                // For leaf section, export pages
                Log.Debug($"Start export pages of section {section.replacedle}");

                var pages = _oneNoteApp.GetPages(sectionNode).Where(p => string.IsNullOrEmpty(pageNameFilter) || p.replacedle == pageNameFilter).ToList();
                var resourceFolderPath = Path.Combine(notebookFolder, "resources");
                Directory.CreateDirectory(resourceFolderPath);

                int cmpt = 0;

                foreach (Page page in pages)
                {
                    Log.Information($"   Page {++cmpt}/{pages.Count} : {page.replacedleWithPageLevelTabulation}");

                    var docxFilePath = Path.Combine(onExportFolder, page.Id + ".docx");

                    try
                    {
                        File.Delete(docxFilePath);

                        Log.Debug($"{page.OneNoteId}: start OneNote docx publish");
                        _oneNoteApp.Publish(page.OneNoteId, Path.GetFullPath(docxFilePath), PublishFormat.pfWord);
                        Log.Debug($"{page.OneNoteId}: success");

                        var mdFilePath = Path.Combine(notebookFolder, $"{page.Id}.md");

                        // Convert docx file into Md using PanDoc
                        var pageMdFileContent = _convertServer.ConvertDocxToMd(page, docxFilePath, resourceFolderPath, section.GetLevel());

                        try
                        {
                            // Copy images extracted from DocX to Export folder and add them in list of attachments of the note
                            pageMdFileContent = _convertServer.ExtractImagesToResourceFolder(page, pageMdFileContent, resourceFolderPath, mdFilePath, true, _appSettings.PostProcessingMdImgRef);
                        }
                        catch (Exception ex)
                        {
                            Log.Warning($"Page '{page.GetPageFileRelativePath()}': {Localizer.GetString("ErrorImageExtract")}");
                            Log.Debug(ex, ex.Message);
                        }

                        // Export all page attachments
                        pageMdFileContent = ExportPageAttachments(page, pageMdFileContent, notebookFolder, resourceFolderPath);

                        // Apply post processing to Page Md content
                        pageMdFileContent = _convertServer.PostConvertion(page, pageMdFileContent, resourceFolderPath, mdFilePath, true);

                        pageMdFileContent = AddJoplinNodeMetadata(page, pageMdFileContent);

                        // Create page md file
                        File.WriteAllText(mdFilePath, pageMdFileContent);


                        if (!_appSettings.Debug)
                        {
                            File.Delete(docxFilePath);
                        }

                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, Localizer.GetString("ErrorDuringPageProcessing"), page.replacedleWithPageLevelTabulation, page.Id, ex.Message);
                    }
                }
            }
        }

19 Source : ModPacker.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

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

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

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

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

                AbortPatch();

                return;
            }

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

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

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

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

                    AbortPatch();

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

                AbortPatch();

                return;
            }

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

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

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

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

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

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

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

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

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

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

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

                    proc.WaitForExit();
                }

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

                // Delete excess files in APK

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

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

                


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

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

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

                // Create wrapper

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

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

                    proc.WaitForExit();
                }

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

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

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

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

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

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

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


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

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

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

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

            ZipFile.CreateFromDirectory(tempProfilePath, output);

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

19 Source : Program.cs
with MIT License
from AmazingDM

public static void Main(string[] args)
        {
            var result = false;

            try
            {
                #region Check Arguments

                if (CurrentProcess.MainModule == null)
                {
                    Console.WriteLine("Current Process MainModule is null");
                    return;
                }

                if (args.Length != 3)
                {
                    Console.WriteLine("The program is not user-oriented\n此程序不是面向用户的");
                    return;
                }

                // arg0 port
                if (!int.TryParse(args[0], out var port))
                {
                    Console.WriteLine("arg0 Port Parse failed");
                    return;
                }

                var updateExtracted = true;
                // arg1 update File/Directory
                var updatePath = Path.GetFullPath(args[1]);
                if (File.Exists(updatePath))
                {
                    updateExtracted = false;
                }
                else if (!Directory.Exists(updatePath))
                {
                    Console.WriteLine("arg1 update file/directory Not found");
                    return;
                }

                // arg2 target Directory
                string targetPath;
                if (!File.Exists(Path.Combine(targetPath = Path.GetFullPath(args[2]), "Netch.exe")))
                {
                    Console.Write("arg2 Netch Directory doesn't seems right");
                    return;
                }

                #region if under target Directory,then rerun in temp directory

                if (UpdaterDirectory.StartsWith(targetPath))
                {
                    // Updater 在目标目录下
                    // 将程序复制到临时目录,传递参数
                    var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                    var newUpdaterPath = Path.Combine(tempPath, UpdaterFriendlyName);
                    Directory.CreateDirectory(tempPath);
                    File.Copy(UpdaterFullName, newUpdaterPath);
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = newUpdaterPath,
                        Arguments = $"{port} \"{updatePath}\" \"{targetPath}\"",
                        WorkingDirectory = tempPath,
                        UseShellExecute = false
                    });
                    result = true;
                    return;
                }

                #endregion

                #endregion

                /*Console.WriteLine("Waiting Attach");
                while (!Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }*/

                #region Send Netch Exit command

                Process[] _;
                if ((_ = Process.GetProcessesByName("Netch")).Any())
                {
                    Console.WriteLine("Found Netch process, Send exit command");
                    try
                    {
                        var udpClient = new UdpClient("127.0.0.1", port);
                        var sendBytes = Encoding.ASCII.GetBytes("Exit");
                        udpClient.Send(sendBytes, sendBytes.Length);
                    }
                    catch
                    {
                        Console.WriteLine("Send command failed");
                        return;
                    }

                    foreach (var proc in _)
                    {
                        try
                        {
                            proc.WaitForExit();
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }
                }

                #endregion

                var counter = 0;
                while (!TestFileFree(Path.Combine(targetPath, "Netch.exe")))
                {
                    // wait 5 sec
                    if (counter > 25)
                    {
                        Console.WriteLine("Waiting Netch exit timeout");
                        return;
                    }

                    Thread.Sleep(200);
                    counter++;
                }

                #region Update

                string extractPath = null;
                if (!updateExtracted)
                {
                    extractPath = Path.Combine(UpdaterDirectory, "extract");
                    Extract(updatePath, extractPath, true);

                    var netchExeFileInfo = FindFile("Netch.exe", extractPath);

                    if (netchExeFileInfo == null)
                    {
                        throw new Exception("Netch.exe not found in archive!");
                    }

                    updatePath = netchExeFileInfo.Directory.FullName;
                }

                MoveDirectory(updatePath, targetPath, true);

                try
                {
                    if (extractPath != null)
                        Directory.Delete(extractPath, true);
                }
                catch
                {
                    // ignored
                }

                #endregion

                #region Finished Update,Start Netch

                Console.WriteLine("Start Netch");
                Process.Start(new ProcessStartInfo
                {
                    FileName = Path.Combine(targetPath, "Netch.exe"),
                    UseShellExecute = true,
                });

                #endregion

                result = true;
            }
            catch (Exception e)
            {
                if (e is InvalidDataException)
                    Console.WriteLine("Archive file Broken");
                Console.WriteLine(e.ToString());
            }
            finally
            {
                if (!result)
                {
                    Console.WriteLine("Press any key to exit...");
                    Console.Read();
                }
            }
        }

19 Source : ModPacker.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

private void AbortPatch()
        {
            // Unload files
            isOriginalLoaded = false;
            isModLoaded = false;
            isApkLoaded = false;
            isLinuxLoaded = false;
            originalPath = "";
            modPath = "";
            apkPath = "";
            linuxPath = "";
            saveFilePath = null;

            // Set labels
            CreateLabel.Text = "Mod packaging aborted!";
            OriginalLabel.Visible = false;
            ModLabel.Visible = false;
            ApkLabel.Visible = false;
            linuxLabel.Visible = false;

            // Remove temp directory
            if (Directory.Exists(Path.GetTempPath() + "\\AM2RModPacker"))
            {
                Directory.Delete(Path.GetTempPath() + "\\AM2RModPacker", true);
            }
        }

19 Source : SelfUpdateProgressPage.cs
with GNU General Public License v3.0
from Amebis

public override void OnActivate()
        {
            base.OnActivate();

            // Setup self-update.
            var selfUpdate = new BackgroundWorker() { WorkerReportsProgress = true };
            selfUpdate.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                selfUpdate.ReportProgress(0);
                var random = new Random();
                var tempFolder = Path.GetTempPath();
                var workingFolder = tempFolder + Path.GetRandomFileName() + "\\";
                Directory.CreateDirectory(workingFolder);
                try
                {
                    string installerFilename = null;
                    FileStream installerFile = null;

                    // Download installer.
                    while (DownloadUris.Count > 0)
                    {
                        Window.Abort.Token.ThrowIfCancellationRequested();
                        var uriIndex = random.Next(DownloadUris.Count);
                        try
                        {
                            var binaryUri = DownloadUris[uriIndex];
                            Trace.TraceInformation("Downloading installer file from {0}...", binaryUri.AbsoluteUri);
                            var request = WebRequest.Create(binaryUri);
                            request.Proxy = null;
                            using (var response = request.GetResponse())
                            {
                                // 1. Get installer filename from Content-Disposition header.
                                // 2. Get installer filename from the last segment of URI path.
                                // 3. Fallback to a predefined installer filename.
                                try { installerFilename = Path.GetFullPath(workingFolder + new ContentDisposition(request.Headers["Content-Disposition"]).FileName); }
                                catch
                                {
                                    try { installerFilename = Path.GetFullPath(workingFolder + binaryUri.Segments[binaryUri.Segments.Length - 1]); }
                                    catch { installerFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup.exe"); }
                                }

                                // Save response data to file.
                                installerFile = File.Open(installerFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                                try
                                {
                                    using (var stream = response.GetResponseStream())
                                    {
                                        installerFile.Seek(0, SeekOrigin.Begin);
                                        var hash = new eduEd25519.SHA256();
                                        var buffer = new byte[1048576];
                                        long offset = 0, total = response.ContentLength;

                                        for (; ; )
                                        {
                                            // Wait for the data to arrive.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            var bufferLength = stream.Read(buffer, 0, buffer.Length);
                                            if (bufferLength == 0)
                                                break;
                                            //Window.Abort.Token.WaitHandle.WaitOne(100); // Mock a slow link for testing.

                                            // Append it to the file and hash it.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            installerFile.Write(buffer, 0, bufferLength);
                                            hash.TransformBlock(buffer, 0, bufferLength, buffer, 0);

                                            // Report progress.
                                            offset += bufferLength;
                                            selfUpdate.ReportProgress((int)(offset * 100 / total));
                                        }

                                        hash.TransformFinalBlock(buffer, 0, 0);
                                        if (!hash.Hash.SequenceEqual(Hash))
                                            throw new DownloadedFileCorruptException(string.Format(Resources.Strings.ErrorDownloadedFileCorrupt, binaryUri.AbsoluteUri));

                                        installerFile.SetLength(installerFile.Position);
                                        break;
                                    }
                                }
                                catch
                                {
                                    // Close installer file.
                                    installerFile.Close();
                                    installerFile = null;

                                    // Delete installer file. If possible.
                                    Trace.TraceInformation("Deleting file {0}...", installerFilename);
                                    try { File.Delete(installerFilename); }
                                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
                                    installerFilename = null;

                                    throw;
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex)
                        {
                            Trace.TraceWarning("Error: {0}", ex.ToString());
                            DownloadUris.RemoveAt(uriIndex);
                        }
                    }

                    if (installerFilename == null || installerFile == null)
                    {
                        // The installer file is not ready.
                        throw new InstallerFileUnavailableException();
                    }

                    try
                    {
                        var updaterFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup and Relaunch.wsf");
                        var updaterFile = File.Open(updaterFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                        try
                        {
                            // Prepare WSF file.
                            var writer = new XmlTextWriter(updaterFile, null);
                            writer.WriteStartDoreplacedent();
                            writer.WriteStartElement("package");
                            writer.WriteStartElement("job");

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "WScript.Shell");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "Scripting.FileSystemObject");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("script");
                            writer.WriteAttributeString("language", "JScript");
                            var installerArgumentsEsc = string.IsNullOrEmpty(Arguments) ? "" : " " + HttpUtility.JavaScriptStringEncode(Arguments);
                            var argv = Environment.GetCommandLineArgs();
                            var arguments = new StringBuilder();
                            for (long i = 1, n = argv.LongLength; i < n; i++)
                            {
                                if (i > 1) arguments.Append(" ");
                                arguments.Append("\"");
                                arguments.Append(argv[i].Replace("\"", "\"\""));
                                arguments.Append("\"");
                            }
                            var script = new StringBuilder();
                            script.AppendLine("var wsh = WScript.CreateObject(\"WScript.Shell\");");
                            script.AppendLine("wsh.Run(\"\\\"" + HttpUtility.JavaScriptStringEncode(installerFilename.Replace("\"", "\"\"")) + "\\\"" + installerArgumentsEsc + "\", 0, true);");
                            script.AppendLine("var fso = WScript.CreateObject(\"Scripting.FileSystemObject\");");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(installerFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(updaterFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFolder(\"" + HttpUtility.JavaScriptStringEncode(workingFolder.TrimEnd(Path.DirectorySeparatorChar)) + "\", true); } catch (err) {}");
                            writer.WriteCData(script.ToString());
                            writer.WriteEndElement(); // script

                            writer.WriteEndElement(); // job
                            writer.WriteEndElement(); // package
                            writer.WriteEndDoreplacedent();
                            writer.Flush();

                            // Prepare WSF launch parameters.
                            Trace.TraceInformation("Launching update script file {0}...", updaterFilename);
                            var process = new Process();
                            process.StartInfo.FileName = "wscript.exe";
                            process.StartInfo.Arguments = "\"" + updaterFilename + "\"";
                            process.StartInfo.WorkingDirectory = workingFolder;

                            // Close WSF and installer files as late as possible to narrow the attack window.
                            // If Windows supported executing files that are locked for writing, we could leave those files open.
                            updaterFile.Close();
                            installerFile.Close();
                            process.Start();
                        }
                        catch
                        {
                            // Close WSF file.
                            updaterFile.Close();

                            // Delete WSF file. If possible.
                            Trace.TraceInformation("Deleting file {0}...", updaterFilename);
                            try { File.Delete(updaterFilename); }
                            catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", updaterFilename, ex2.ToString()); }

                            throw;
                        }
                    }
                    catch
                    {
                        // Close installer file.
                        installerFile.Close();

                        // Delete installer file. If possible.
                        Trace.TraceInformation("Deleting file {0}...", installerFilename);
                        try { File.Delete(installerFilename); }
                        catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }

                        throw;
                    }
                }
                catch
                {
                    // Delete working folder. If possible.
                    try { Directory.Delete(workingFolder); }
                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} folder failed: {1}", workingFolder, ex2.ToString()); }

                    throw;
                }
            };

            // Self-update progress.
            selfUpdate.ProgressChanged += (object sender, ProgressChangedEventArgs e) =>
            {
                Progress.Value = e.ProgressPercentage;
            };

            // Self-update complereplacedion.
            selfUpdate.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                if (e.Error == null)
                {
                    // Self-updating successfuly launched. Quit to release open files.
                    Wizard.OnQuitApplication(this);
                }
                else
                    Wizard.Error = e.Error;

                // Self-dispose.
                (sender as BackgroundWorker)?.Dispose();
            };

            selfUpdate.RunWorkerAsync();
        }

19 Source : TempFileManager.cs
with Apache License 2.0
from AmpScm

public string GetTempFile()
        {
            string name = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));

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

19 Source : TempDirManager.cs
with Apache License 2.0
from AmpScm

public string GetTempDir()
        {
            string name = "";
            string tempPath = SvnTools.GetNormalizedFullPath(Path.GetTempPath());
            for (int i = 4; i < 32; i += 2)
            {
                name = Path.Combine(tempPath, "AnkhSVN\\" + Guid.NewGuid().ToString("N").Substring(0, i));

                if (!SvnItem.PathExists(name))
                    break;
            }
            Directory.CreateDirectory(name);
            _tempDirs.AddDirectory(name, false);
            return name;
        }

19 Source : TempFileManager.cs
with Apache License 2.0
from 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 Source : FileIconMapper.cs
with Apache License 2.0
from AmpScm

static string GetTypeNameForExtension(string extension)
        {
            Debug.replacedert(!string.IsNullOrEmpty(extension));

            string dummyPath = Path.Combine(Path.GetTempPath(), "Dummy." + extension);

            NativeMethods.SHFILEINFO fileinfo = new NativeMethods.SHFILEINFO();
            IntPtr rslt = NativeMethods.SHGetFileInfoW(dummyPath, (uint)(FileAttributes.Normal), ref fileinfo,
                (uint)Marshal.SizeOf(fileinfo), NativeMethods.SHGFI_TYPENAME | NativeMethods.SHGFI_USEFILEATTRIBUTES);

            if (rslt == IntPtr.Zero)
                return null;

            return fileinfo.szTypeName;
        }

19 Source : CommandRoutingTest.cs
with Apache License 2.0
from AmpScm

[Test, Explicit("Broken")]
        public void AddWorkingCopyExplorerRootCommandWithPath()
        {
            ISelectionContext selC = SelectionContextMock.EmptyContext();
            using (ServiceProviderHelper.AddService(typeof(ISelectionContext), selC))
            {
                replacedert.IsTrue(CommandTester.TestExecution(AnkhCommand.WorkingCopyBrowse, Path.GetTempPath()));
            }
        }

19 Source : FileIconMapperTest.cs
with Apache License 2.0
from AmpScm

[Test]
        public void TestExistingFileType()
        {
            var statusCache = new Mock<ISvnStatusCache>();

            string tempFile = Path.GetTempFileName();
            string exeTempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".exe");
            using (File.CreateText(exeTempFile))
            { }

            try
            {
                var item = new SvnItem(statusCache.Object, tempFile, NoSccStatus.Unknown, SharpSvn.SvnNodeKind.File);
                replacedert.That(mapper.GetFileType(item), Is.EqualTo("TMP File"));

                item = new SvnItem(statusCache.Object, exeTempFile, NoSccStatus.Unknown, SharpSvn.SvnNodeKind.File);
                replacedert.That(mapper.GetFileType(item), Is.EqualTo("Application"));

                item = new SvnItem(statusCache.Object, "C:\\", NoSccStatus.Unknown, SharpSvn.SvnNodeKind.Directory);
                replacedert.That(mapper.GetFileType(item), Is.EqualTo("Local Disk"));
            }
            finally
            {
                File.Delete(tempFile);
                File.Delete(exeTempFile);
            }
        }

19 Source : FileIconMapperTest.cs
with Apache License 2.0
from AmpScm

[Test]
        public void TestGetIcon()
        {
            var tempFileName = Path.Combine(Path.GetTempPath(), Path.GetTempFileName() + ".txt");
            using(File.Create(tempFileName))
            {
            }

            try
            {
                var icon = mapper.GetIcon(tempFileName);
                replacedert.That(icon, Is.GreaterThan(-1));
            }
            finally
            {
                File.Delete(tempFileName);
            }
        }

19 Source : FileProcessor.cs
with MIT License
from Analogy-LogViewer

private string UnzipFilesIntoTempFolder(string zipPath, IreplacedogyOfflineDataProvider fileDataProvider)
        {
            string extractPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(extractPath);
            if (zipPath.EndsWith("zip", StringComparison.InvariantCultureIgnoreCase))
            {
                UnzipZipFileIntoTempFolder(zipPath, extractPath, fileDataProvider);
            }
            else if (zipPath.EndsWith("gz", StringComparison.InvariantCultureIgnoreCase))
            {
                UnzipGzFileIntoTempFolder(zipPath, extractPath);
            }
            else
            {
                replacedogyLogger.Instance.LogError(nameof(UnzipFilesIntoTempFolder), $"Unsupported file: {zipPath}.");
                return string.Empty;
            }

            return extractPath;
        }

19 Source : Program.cs
with MIT License
from ANF-Studios

[SupportedOSPlatform("windows")]
        [UnsupportedOSPlatform("browser")]
        public static void Main(string[] args)
        {
            Console.replacedle = AppDomain.CurrentDomain.FriendlyName;
            if (!OperatingSystem.IsWindows())
                throw new PlatformNotSupportedException("WinPath is Windows only!");
            Parser.Default.ParseVerbs<AddOptions, BackupOptions, UpdateOptions>(args)
                .WithParsed<AddOptions>(options => {
                    if (options.Value == null) HandleArgument(HandleEventType.NoValue);
                    else if (options.Value != null)
                    {
                        if (options.AddToUserVariables && options.AddToSystemVariables)
                            HandleArgument(HandleEventType.UserAndSystemPath, options);
                        else if (options.AddToUserVariables)
                            HandleArgument(HandleEventType.UserPath, options);
                        else if (options.AddToSystemVariables)
                            HandleArgument(HandleEventType.SystemPath, options);
                        else
                            HandleArgument(HandleEventType.NoUserOrSystemPath);
                    }
                })
                //.WithParsed<BackupOptions>(options =>
                //{
                //    Doesn't react/trigger this section.
                //    This is because of child verbs.
                //})
                .WithParsed<BackupOptions.BackupListOptions>(options =>
                {
                    if (options.ListAllBackups)
                        Backup.ListBackups(
                            HandleEventType.ListAllBackups,
                            userPath.BackupDirectory
                        );
                    else if (options.ListLatest)
                        Backup.ListBackups(
                            HandleEventType.ListLatestBackups,
                            userPath.BackupDirectory
                        );
                    else
                        Backup.ListBackups(
                            HandleEventType.ListBackups,
                            userPath.BackupDirectory,
                            null,
                            options.Range
                        );
                })
                .WithParsed<BackupOptions.BackupApplyOptions>(options => Backup.ApplyBackup(options))
                .WithParsed<BackupOptions.BackupCreateOptions>(options => Backup.CreateBackup(options))
                .WithParsed<BackupOptions.BackupRemoveOptions>(options => Backup.RemoveBackup(options))
                .WithParsed<UpdateOptions>(options => {
                    Console.WriteLine("Updating WinPath...");
                    Update update = new Update
                    (
                        options.IncludePrereleases,
                        options.ConfirmDownload,
                        (Runtime.OSArchitecture == Architecture.X86
                            || Runtime.OSArchitecture == Architecture.X64)
                    );
                    Console.WriteLine("Fetching data from the server...");
                    var releases = update.GetReleases();
                    Console.WriteLine("replacedyzing data...");
                    Release? release = update.FilterRelease(releases);
                    
                    // To be removed in v1.0.0.
                    if (release is null)
                    {
                        Console.WriteLine("There is no stable release at the moment, please run this command again with the --prerelease flag.");
                        return;
                    }
                    Console.WriteLine("Parsing data...");
                    ReleaseInfo releaseInfo = new ReleaseInfo
                    {
                        ReleaseName = release?.ReleaseName,
                        TagName = release?.TagName,
                        IsPrerelease = (bool)(release?.IsPrerelease),
                        ReleaseDescription = release?.Description,
                        Releasereplacedet = update.GetreplacedetForProcess((Release)release)!,
                        Updater = (replacedet)release?.replacedets.Find((replacedet) => replacedet.ExecutableName == (
                            update.Is32Or64BitOperatingSystem
                                ? "WinPath.Updater_x86.exe"
                                : "WinPath.Updater_arm.exe" 
                            ))
                    };
                    update.DownloadWinPath(releaseInfo, () => {
                        foreach (string file in
                            Directory.EnumerateFiles(
                                $"{Path.GetTempPath()}WinPath\\download\\"
                        ))
                            try
                            {
                                File.Delete(file);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error cleaning up: " + ex.Message);
                            }
                    });
                });
        }

19 Source : BackupCommandTests.cs
with MIT License
from ANF-Studios

[Fact]
        [SupportedOSPlatform("windows")]
        public void ApplyUserBackup()
        {
            CreateUserBackupInASpecifiedDirectory();
            var backup = Directory.EnumerateFiles(overrideDirectory).ToArray().FirstOrDefault();
            var backupFile = new FileInfo(backup);

            output.WriteLine(backup);
            output.WriteLine(backupFile.Name);

            Program.Main(
                new string[]
                {
                        "backup",
                        "apply",
                        "--user",
                        "--name",
                        backupFile.Name,
                        "--directory",
                        overrideDirectory
                }
            );
            replacedert.True(File.Exists(Path.Combine(Path.GetTempPath(), "WinPath", "u_backup.txt")));
        }

19 Source : Backup.cs
with MIT License
from ANF-Studios

public static void ApplyBackup(in BackupOptions.BackupApplyOptions options)
        {
            // Seems like this not needed, but we're not sure just yet.
            //if (options.BackupDirectory.Contains("-n"))
            //{
            //    Console.WriteLine("Whoops, seems like there's an issue on our end. Please use the --name (-n) flag before --directory (-d).");
            //    return;
            //}

            if (options.RestoreUserVariables && options.RestoreSystemVariables)
            {
                Console.WriteLine("Both user and system variables cannot be restored at the same time (this is to protect you).");
                return;
            }

            if (options.RestoreSystemVariables)
            {
                Console.WriteLine("System variables are not yet supported by the API.");
                return;
            }

            // Invalid chars that may be in the provided directory.
            // For example:
            // When using a command argument `--directory "D:\backups\path\"` It takes the `\"` part
            // as a literal escape character which causes the value to be invalid.
            options.BackupDirectory = options.BackupDirectory.Trim(Path.GetInvalidFileNameChars());

            string file = Path.Combine(options.BackupDirectory, options.BackupFilename);
            string initialUserPath = options.RestoreUserVariables
                                        ? Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User)
                                        : null;
            string initialSystemPath = options.RestoreSystemVariables
                                        ? Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine)
                                        : null;

            if (!File.Exists(file))
            {
                Console.WriteLine(file + " not found! Aborting restore.");
                return;
            }
            else
            {
                string newPath = File.ReadAllText(file);

                if (string.IsNullOrEmpty(newPath))
                {
                    Console.WriteLine("Given file is empty! Aborting restore.");
                    return;
                }

                if (options.RestoreUserVariables)
                {
                    string tempDir = Path.Combine(Path.GetTempPath(), "WinPath");

                    try
                    {
                        if (!Directory.Exists(tempDir))
                            Directory.CreateDirectory(tempDir);
                        File.WriteAllText(userinitialBackup, initialUserPath);
                    }
                    catch (UnauthorizedAccessException) { Console.WriteLine("Whoops, we do not have enough permissions to create a backup before replacing, it's okay though!"); }
                    catch (Exception exception) { Console.WriteLine("There seems to be an error backing up the path before replacing, it's okay though!\nDetails: " + exception.Message); }

                    Environment.SetEnvironmentVariable("Path", newPath, EnvironmentVariableTarget.User);

                    Console.WriteLine("Successfully restored file as new Path!");
                    Console.WriteLine("In case if you changed your mind, there is a backup at: " + userinitialBackup);
                }
                if (options.RestoreSystemVariables)
                {
                    File.WriteAllText(systeminitialBackup, initialSystemPath);

                    Environment.SetEnvironmentVariable("Path", newPath, EnvironmentVariableTarget.Machine);

                    Console.WriteLine("Successfully restored file as new Path!");
                    Console.WriteLine("In case if you changed your mind, there is a backup at: " + systeminitialBackup);
                }
            }
        }

19 Source : NotepadListItem.xaml.cs
with MIT License
from AngryCarrot789

private void GripMouseMove(object sender, MouseEventArgs e)
        {
            bool canDrag;
            if (PreferencesG.USE_NEW_DRAGDROP_SYSTEM && !Model.Notepad.Doreplacedent.FilePath.IsFile())
            {
                Cursor = Cursors.Hand;
                canDrag = true;
            }
            else
            {
                Cursor = Cursors.No;
                canDrag = false;
            }

            if (GripMouseStartPoint != e.GetPosition(null) && e.LeftButton == MouseButtonState.Pressed)
            {
                try
                {
                    if (canDrag)
                    {
                        SetDraggingStatus(true);
                        DragDropFileWatchers.DoingDragDrop(Model.Notepad);
                        string prefixedPath = Path.Combine(Path.GetTempPath(), DragDropNameHelper.GetPrefixedFileName(Model.Notepad.Doreplacedent.FileName));
                        string[] fileList = new string[] { prefixedPath };
                        File.WriteAllText(prefixedPath, Model.Notepad.Doreplacedent.Text);
                        DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, fileList), DragDropEffects.Move);
                        SetDraggingStatus(false);
                    }
                }
                catch { }
            }
        }

19 Source : NotepadListItem.xaml.cs
with MIT License
from AngryCarrot789

private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            // Wrapping the entire thing in a try catch block just incase
            // Had to add a check to the textbox because it can freeze the entire UI
            // if you click and drag over the textbox. idk why though, calls a COM exception.
            if (CanStartDragDrop())
            {
                try
                {
                    Point orgPos = ControlMouseStartPoint;
                    Point newPos = e.GetPosition(this);
                    if (e.LeftButton == MouseButtonState.Pressed)
                    {
                        bool canDoDrag = false;
                        int mouseXDragOffset = 16;
                        int mouseYDragOffset = 10;
                        int edgeOffsetX = 10, edgeOffsetY = 10;

                        // Checks if you drag a bit awawy from where you clicked.
                        if (newPos.X < (orgPos.X - mouseXDragOffset) || newPos.X > (orgPos.X + mouseXDragOffset))
                            canDoDrag = true;
                        if (newPos.Y < (orgPos.Y - mouseYDragOffset) || newPos.Y > (orgPos.Y + mouseYDragOffset))
                            canDoDrag = true;

                        // Checks if you drag near to the edges of the border.
                        if (newPos.X < edgeOffsetX || newPos.X > (ActualWidth - edgeOffsetX))
                            canDoDrag = true;
                        if (newPos.Y < edgeOffsetY || newPos.Y > (ActualHeight - edgeOffsetY))
                            canDoDrag = true;

                        if (canDoDrag)
                        {
                            if (Model.Notepad.Doreplacedent.FilePath.IsFile())
                            {
                                string[] path1 = new string[1] { Model.Notepad.Doreplacedent.FilePath };
                                SetDraggingStatus(true);
                                DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, path1), DragDropEffects.Copy);
                                SetDraggingStatus(false);
                            }
                            else
                            {
                                SetDraggingStatus(true);
                                string tempFilePath = Path.Combine(Path.GetTempPath(), Model.Notepad.Doreplacedent.FileName);
                                File.WriteAllText(tempFilePath, Model.Notepad.Doreplacedent.Text);
                                string[] path = new string[1] { tempFilePath };
                                DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, path), DragDropEffects.Copy);
                                File.Delete(tempFilePath);
                                SetDraggingStatus(false);
                            }
                        }
                    }
                }
                catch { }
            }
        }

19 Source : TopNotepadListItem.xaml.cs
with MIT License
from AngryCarrot789

private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            // Wrapping the entire thing in a try catch block just incase
            // Had to add a check to the textbox because it can freeze the entire UI
            // if you click and drag over the textbox. idk why though, calls a COM exception.
            if (!IsDragging && !fileNameBox.IsMouseOver && !fileNameBox.IsFocused)
            {
                try
                {
                    Point orgPos = ControlMouseStartPoint;
                    Point newPos = e.GetPosition(this);
                    if (e.LeftButton == MouseButtonState.Pressed)
                    {
                        bool canDoDrag = false;
                        int mouseXDragOffset = 24;
                        int mouseYDragOffset = 20;
                        int edgeOffsetX = 10, edgeOffsetY = 10;

                        // Checks if you drag a bit awawy from where you clicked.
                        if (newPos.X < (orgPos.X - mouseXDragOffset) || newPos.X > (orgPos.X + mouseXDragOffset))
                            canDoDrag = true;
                        if (newPos.Y < (orgPos.Y - mouseYDragOffset) || newPos.Y > (orgPos.Y + mouseYDragOffset))
                            canDoDrag = true;

                        // Checks if you drag near to the edges of the border.
                        if (newPos.X < edgeOffsetX || newPos.X > (ActualWidth - edgeOffsetX))
                            canDoDrag = true;
                        if (newPos.Y < edgeOffsetY || newPos.Y > (ActualHeight - edgeOffsetY))
                            canDoDrag = true;

                        if (canDoDrag)
                        {
                            if (Model.Notepad.Doreplacedent.FilePath.IsFile())
                            {
                                string[] path1 = new string[1] { Model.Notepad.Doreplacedent.FilePath };
                                SetDraggingStatus(true);
                                DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, path1), DragDropEffects.Copy);
                                SetDraggingStatus(false);
                            }
                            else
                            {
                                SetDraggingStatus(true);
                                string tempFilePath = Path.Combine(Path.GetTempPath(), Model.Notepad.Doreplacedent.FileName);
                                File.WriteAllText(tempFilePath, Model.Notepad.Doreplacedent.Text);
                                string[] path = new string[1] { tempFilePath };
                                DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, path), DragDropEffects.Copy);
                                File.Delete(tempFilePath);
                                SetDraggingStatus(false);
                            }
                        }
                    }
                }
                catch { }
            }
        }

19 Source : NotepadViewModel.cs
with MIT License
from AngryCarrot789

public void OpenNotepadDoreplacedentInNewView(NotepadItemViewModel nli)
        {
            if (nli != null)
            {
                TextDoreplacedentViewModel doc = nli.Notepad;

                if (doc == null)
                    return;

                if (File.Exists(doc.Doreplacedent.FilePath))
                {
                    ThisApplication.OpenFileInNewWindow(doc.Doreplacedent.FilePath, false, false);
                    Information.Show($"Opened [{doc.Doreplacedent.FileName}] in another window", InfoTypes.Information);
                    CloseNotepadItem(nli, false);
                }
                else
                {
                    string tempFilePath = Path.Combine(Path.GetTempPath(), doc.Doreplacedent.FileName);
                    File.WriteAllText(tempFilePath, doc.Doreplacedent.Text);
                    ThisApplication.OpenFileInNewWindow(tempFilePath, true, false);
                    Information.Show($"Opened [{doc.Doreplacedent.FileName}] in another window", InfoTypes.Information);
                    CloseNotepadItem(nli, false);
                    File.Delete(tempFilePath);
                }
            }
        }

19 Source : WidgetView.xaml.cs
with MIT License
from anoyetta

public static void InitializeCef()
        {
            lock (CefLocker)
            {
                if (isInitialized)
                {
                    return;
                }

                isInitialized = true;
            }

            var settings = new CefSettings();

            settings.BrowserSubprocessPath = Path.Combine(
                AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                Environment.Is64BitProcess ? "x64" : "x86",
                "CefSharp.BrowserSubprocess.exe");

            settings.Locale = CultureInfo.CurrentCulture.Parent.ToString();
            settings.AcceptLanguageList = CultureInfo.CurrentCulture.Name;

            settings.CachePath = Path.Combine(
                Path.GetTempPath(),
                "XIVNote");
            settings.LogFile = Path.Combine(
                Path.GetTempPath(),
                "XIVNote",
                "browser.log");
            settings.LogSeverity = LogSeverity.Warning;

            // GPUアクセラレータを切る
            settings.DisableGpuAcceleration();

            Cef.EnableHighDPISupport();
            Cef.Initialize(settings);

            // shutdown を仕込む
            App.Current.Exit += (_, __) => Cef.Shutdown();
        }

19 Source : UpdateCheckerViewModel.cs
with MIT License
from anoyetta

private async void ExecuteUpdate()
        {
            var model = this.Model.Value;
            var temp = Path.GetTempFileName() + ".zip";
            var extractDirectory = string.Empty;
            var result = MessageDialogResult.Negative;

            try
            {
                this.InProgress.Value = true;

                // ダウンロードする
                this.CurrentProgressMessage.Value = "Downloading...";
                await model.DownloadAsync(
                    temp,
                    (sender, e) =>
                    {
                        Application.Current.Dispatcher.InvokeAsync(() =>
                        {
                            this.Maximum.Value = e.TotalBytesToReceive;
                            this.CurrentValue.Value = e.BytesReceived;
                        });
                    });

                await Task.Delay(100);

                // 展開する
                this.CurrentProgressMessage.Value = "Extracting...";

                extractDirectory = Path.Combine(
                    Path.GetTempPath(),
                    $"{this.AppName.Value}_v{model.Version}_{model.ReleaseChannel}");

                if (Directory.Exists(extractDirectory))
                {
                    Directory.Delete(extractDirectory, true);
                }

                ZipFile.ExtractToDirectory(
                    temp,
                    extractDirectory);

                // 準備完了
                this.CurrentProgressMessage.Value = "Update Ready.";
                await Task.Delay(100);

                if (this.CloseViewCallback != null)
                {
                    WPFHelper.Dispatcher.Invoke(this.CloseViewCallback);
                    await Task.Delay(50);
                }

                // 最後の確認?
                result = await MessageBoxHelper.ShowMessageAsync(
                    "Application Updater",
                    "アップデートの準備が完了しました。\n" +
                    "アプリケーションを再起動してアップデートを実行しますか?",
                    MessageDialogStyle.AffirmativeAndNegative,
                    new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "はい",
                        NegativeButtonText = "いいえ",
                        AnimateHide = true,
                        AnimateShow = true,
                        DefaultButtonFocus = MessageDialogResult.Negative
                    });
            }
            finally
            {
                if (File.Exists(temp))
                {
                    File.Delete(temp);
                }

                this.InProgress.Value = false;
                this.CurrentProgressMessage.Value = string.Empty;
            }

            if (result != MessageDialogResult.Affirmative)
            {
                return;
            }

            const string UpdaterFileName = "aframe.Updater.exe";

            var target = this.Targetreplacedembly.Value?.Location;
            var destination = Path.GetDirectoryName(target);
            var sourceUpdater = Path.Combine(
                extractDirectory,
                UpdaterFileName);

            var pi = new ProcessStartInfo(sourceUpdater)
            {
                Arguments = string.Join(" ", new[]
                {
                    $@"""{target}""",
                    $@"""{extractDirectory}""",
                    $@"""{destination}"""
                }),
                WorkingDirectory = extractDirectory
            };

            Process.Start(pi);

            if (UpdateChecker.ShutdownCallback != null)
            {
                Thread.Sleep(50);
                UpdateChecker.ShutdownCallback.Invoke();
            }
        }

19 Source : IconExtractor.cs
with GNU General Public License v3.0
from antikmozib

public static ImageSource Extract(string destination, string url, bool isDirectory)
        {
            Shell32.SHFILEINFO shinfo = new Shell32.SHFILEINFO();
            ImageSource imageSource;
            string alternatePath = destination;
            bool deleteFile = false;
            string ext = Path.GetExtension(destination);
            string shortFilename = Path.GetFileName(destination);
            Icon icon;

            // have we seen these before?
            if (isDirectory && _icons.ContainsKey(destination))
            {
                _icons.TryGetValue(destination, out imageSource);
                return imageSource;
            }
            else if (!isDirectory && ext != ".exe" && _icons.ContainsKey(ext))
            {
                _icons.TryGetValue(ext, out imageSource);
                return imageSource;
            }
            else if (!isDirectory && ext == ".exe" && _icons.ContainsKey(shortFilename))
            {
                _icons.TryGetValue(shortFilename, out imageSource);
                return imageSource;
            }

            // check paths and create temp files if necessary
            if (isDirectory && !Directory.Exists(destination))
            {
                alternatePath = AppDomain.CurrentDomain.BaseDirectory;
            }
            else if (!isDirectory && !File.Exists(destination))
            {
                ext = Path.GetExtension(destination).ToLower();
                alternatePath = Path.GetTempPath() + Path.DirectorySeparatorChar + "AMDownloader" + DateTime.Now.ToFileTimeUtc() + "." + ext;
                File.Create(alternatePath).Close();
                deleteFile = true;
            }

            // grab the actual icons
            if (!isDirectory)
            {
                // file icon
                icon = Icon.ExtractreplacedociatedIcon(alternatePath);
            }
            else
            {
                // folder icon
                Shell32.SHGetFileInfo(
                    alternatePath,
                    Shell32.FILE_ATTRIBUTE_NORMAL,
                    ref shinfo,
                    (uint)Marshal.SizeOf(shinfo),
                    Shell32.SHGFI_ICON | Shell32.SHGFI_LARGEICON);

                icon = Icon.FromHandle(shinfo.hIcon);
            }

            // create the image from the icon
            imageSource = Imaging.CreateBitmapSourceFromHIcon(
                icon.Handle,
                new Int32Rect(0, 0, icon.Width, icon.Height),
                BitmapSizeOptions.FromEmptyOptions());

            // save the keys and images
            if (isDirectory && !_icons.ContainsKey(alternatePath))
            {
                _icons.Add(alternatePath, imageSource);
            }
            else
            {
                if (ext != ".exe" && !_icons.ContainsKey(ext))
                {
                    _icons.Add(ext, imageSource);
                }
                else if (ext == ".exe" && File.Exists(destination))
                {
                    _icons.Add(shortFilename, imageSource);
                }
            }

            if (deleteFile)
            {
                File.Delete(alternatePath);
            }

            if (isDirectory)
            {
                User32.DestroyIcon(shinfo.hIcon);
            }

            return imageSource;
        }

19 Source : FileUtils.cs
with MIT License
from AntonyCorbett

public static string GetUsersTempStagingFolder()
        {
            return Path.Combine(Path.GetTempPath(), AppNamePathSegment, "Slideshows");
        }

19 Source : FileUtils.cs
with MIT License
from AntonyCorbett

public static string GetUsersTempFolder()
        {
            return Path.GetTempPath();
        }

19 Source : FileUtils.cs
with MIT License
from AntonyCorbett

public static string GetUsersTempFolder() => Path.GetTempPath();

19 Source : FileUtils.cs
with MIT License
from AntonyCorbett

public static string GetSystemTempFolder()
        {
            return Path.GetTempPath();
        }

19 Source : TestTimingReport.cs
with MIT License
from AntonyCorbett

private static void WriteReport(
            DateTimeServiceForTests dateTimeService, 
            IQueryWeekendService queryWeekendService,
            MeetingTimes lastMtgTimes)
        {
            var service = new LocalTimingDataStoreService(null, dateTimeService);
            var historicalTimes = service.GetHistoricalMeetingTimes();

            var report = new PdfTimingReport(
                lastMtgTimes, 
                historicalTimes,
                queryWeekendService,
                false,
                Path.GetTempPath());

            report.Execute();
        }

19 Source : FileUtils.cs
with MIT License
from AntonyCorbett

public static string GetTempOnlyVFolder()
        {
            return Path.Combine(Path.GetTempPath(), AppNamePathSegment);
        }

19 Source : ThemeFile.cs
with MIT License
from 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 Source : DatasetTests.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

[Theory]
        [InlineData("absolute")]
        [InlineData("relative")]
        [InlineData("prefix")]
        public void CanReadDataset_External(string datasetName)
        {
            // INFO:
            // HDF lib says "external storage not supported with chunked layout". Same is true for compact layout.
            
            TestUtils.RunForAllVersions(version =>
            {
                // Arrange
                var absolutePrefix = datasetName == "absolute" 
                    ? Path.GetTempPath() 
                    : string.Empty;

                var externalFilePrefix = datasetName == "prefix"
                   ? Path.GetTempPath()
                   : null;

                var datasetAccess = new H5DatasetAccess()
                {
                    ExternalFilePrefix = externalFilePrefix
                };

                var filePath = TestUtils.PrepareTestFile(version, fileId => TestUtils.AddExternalDataset(fileId, datasetName, absolutePrefix, datasetAccess));
                var expected = TestData.MediumData.ToArray();

                for (int i = 33; i < 40; i++)
                {
                    expected[i] = 0;
                }

                // Act
                using var root = H5File.OpenReadCore(filePath, deleteOnClose: true);
                var parent = root.Group("external");
                var dataset = parent.Dataset(datasetName);
                var actual = dataset.Read<int>();

                // replacedert
                replacedert.True(actual.SequenceEqual(expected));
            });
        }

19 Source : LinkTests.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

[Theory]
        [InlineData("absolute", "", "")] // direct access
        [InlineData("relative", "single", "")] // use environment variable
        //[InlineData("relative", "multiple", "")] // this test will fail on Windows because of colon in path
        [InlineData("relative", "", "yes")] // use link access property list
        [InlineData("relative", "", "")] // file sits next to calling file
        [InlineData("relativecd", "", "")] // file sits next to current directory
        public void CanFollowExternalLink(string externalFilePath, string environment, string prefix)
        {
            // Arrange
            if (externalFilePath == "absolute")
            {
                externalFilePath = Path.GetTempFileName();
            }

            var filePath = TestUtils.PrepareTestFile(H5F.libver_t.LATEST, fileId => TestUtils.AddExternalFileLink(fileId, externalFilePath));

            if (externalFilePath == "relative")
                externalFilePath = Path.Combine(Path.GetTempPath(), externalFilePath);
            else if (externalFilePath == "relativecd")
                externalFilePath = Path.Combine(Environment.CurrentDirectory, externalFilePath);

            if (environment == "single")
            {
                environment = Path.GetDirectoryName(externalFilePath);
                Environment.SetEnvironmentVariable("HDF5_EXT_PREFIX", environment);
            }
            else if (environment == "multiple")
            {
                // Why did HDF Group choose a colon as prefix separator? This test must fail.
                environment = $"::C:\\temp:{Path.GetDirectoryName(externalFilePath)}";
                Environment.SetEnvironmentVariable("HDF5_EXT_PREFIX", environment);
            }

            if (prefix == "yes")
                prefix = Path.GetDirectoryName(externalFilePath);

            long res;

            var externalFileId = H5F.create(externalFilePath, H5F.ACC_TRUNC);
            var externalGroupId1 = H5G.create(externalFileId, "external");
            var externalGroupId2 = H5G.create(externalGroupId1, "group");

            var spaceId = H5S.create_simple(1, new ulong[] { 1 }, new ulong[] { 1 });
            var datasetId = H5D.create(externalGroupId2, "Hello from external file =)", H5T.NATIVE_UINT, spaceId);

            res = H5S.close(spaceId);
            res = H5D.close(datasetId);
            res = H5G.close(externalGroupId2);
            res = H5G.close(externalGroupId1);
            res = H5F.close(externalFileId);

            // Act
            using var root = H5File.OpenReadCore(filePath, deleteOnClose: true);

            var linkAccess = string.IsNullOrWhiteSpace(prefix) 
                ? new H5LinkAccess()
                : new H5LinkAccess() { ExternalLinkPrefix = prefix };

            var dataset = root.Dataset("/links/external_link/Hello from external file =)", linkAccess);
        }

19 Source : CommentsTest.cs
with Apache License 2.0
from Appdynamics

[TestMethod]
        public void VisibilityComments()
        {
            var xlsxName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xlsx");
            try
            {
                using (var ms = File.Open(xlsxName, FileMode.OpenOrCreate))
                using (var pkg = new ExcelPackage(ms))
                {
                    var ws = pkg.Workbook.Worksheets.Add("Comment");
                    var a1 = ws.Cells["A1"];
                    a1.Value = "Justin Dearing";
                    a1.AddComment("I am A1s comment", "JD");
                    replacedert.IsFalse(a1.Comment.Visible); // Comments are by default invisible 
                    a1.Comment.Visible = true;
                    a1.Comment.Visible = false;
                    replacedert.IsNotNull(a1.Comment);
                    //check style attribute
                    var stylesDict = new System.Collections.Generic.Dictionary<string, string>();
                    string[] styles = a1.Comment.Style
                        .Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach(var s in styles)
                    {
                        string[] split = s.Split(':');
                        if (split.Length == 2)
                        {
                            var k = (split[0] ?? "").Trim().ToLower();
                            var v = (split[1] ?? "").Trim().ToLower();
                            stylesDict[k] = v;
                        }
                    }
                    replacedert.IsTrue(stylesDict.ContainsKey("visibility"));
                    //replacedert.AreEqual("visible", stylesDict["visibility"]);
                    replacedert.AreEqual("hidden", stylesDict["visibility"]);
                    replacedert.IsFalse(a1.Comment.Visible);
                    pkg.Save();
                    ms.Close();
                }
            }
            finally
            {
                //open results file in program for view xlsx.
                //comments of cell A1 must be hidden.
                //System.Diagnostics.Process.Start(Path.GetDirectoryName(xlsxName));
                File.Delete(xlsxName);
            }
        }

19 Source : Issues.cs
with Apache License 2.0
from Appdynamics

[TestMethod, Ignore]
        public void MergeIssue()
        {
            var worksheetPath = Path.Combine(Path.GetTempPath(), @"EPPlus worksheets");
            FileInfo fi = new FileInfo(Path.Combine(worksheetPath, "Example.xlsx"));
            fi.Delete();
            using (ExcelPackage pckg = new ExcelPackage(fi))
            {
                var ws = pckg.Workbook.Worksheets.Add("Example");
                ws.Cells[1, 1, 1, 3].Merge = true;
                ws.Cells[1, 1, 1, 3].Merge = true;
                pckg.Save();
            }
        }

19 Source : Issues.cs
with Apache License 2.0
from Appdynamics

[TestMethod]
        public void Issue63() // See https://github.com/JanKallman/EPPlus/issues/63
        {
            // Prepare
            var newFile = new FileInfo(Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.xlsx"));
            try
            {
                using (var package = new ExcelPackage(newFile))
                {
                    ExcelWorksheet ws = package.Workbook.Worksheets.Add("ArrayTest");
                    ws.Cells["A1"].Value = 1;
                    ws.Cells["A2"].Value = 2;
                    ws.Cells["A3"].Value = 3;
                    ws.Cells["B1:B3"].CreateArrayFormula("A1:A3");
                    package.Save();
                }
                replacedert.IsTrue(File.Exists(newFile.FullName));

                // Test: basic support to recognize array formulas after reading Excel workbook file
                using (var package = new ExcelPackage(newFile))
                {
                    replacedert.AreEqual("A1:A3", package.Workbook.Worksheets["ArrayTest"].Cells["B1"].Formula);
                    replacedert.IsTrue(package.Workbook.Worksheets["ArrayTest"].Cells["B1"].IsArrayFormula);
                }
            }
            finally
            {
                File.Delete(newFile.FullName);
            }
        }

19 Source : TestBase.cs
with Apache License 2.0
from Appdynamics

[TestInitialize]
        public void InitBase()
        {
            _clipartPath = Path.Combine(Path.GetTempPath(), @"EPPlus clipart");
            if (!Directory.Exists(_clipartPath))
            {
                Directory.CreateDirectory(_clipartPath);
            }
            if(Environment.GetEnvironmentVariable("EPPlusTestInputPath")!=null)
            {
                _testInputPath = Environment.GetEnvironmentVariable("EPPlusTestInputPath");
            }
            var asm = replacedembly.GetExecutingreplacedembly();
            var validExtensions = new[]
                {
                    ".gif", ".wmf"
                };

            foreach (var name in asm.GetManifestResourceNames())
            {
                foreach (var ext in validExtensions)
                {
                    if (name.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
                    {
                        string fileName = name.Replace("EPPlusTest.Resources.", "");
                        using (var stream = asm.GetManifestResourceStream(name))
                        using (var file = File.Create(Path.Combine(_clipartPath, fileName)))
                        {
                            stream.CopyTo(file);
                        }
                        break;
                    }
                }
            }
            
            //_worksheetPath = Path.Combine(Path.GetTempPath(), @"EPPlus worksheets");
            //if (!Directory.Exists(_worksheetPath))
            //{
            //    Directory.CreateDirectory(_worksheetPath);
            //}
            var di=new DirectoryInfo(_worksheetPath);            
            _worksheetPath = di.FullName + "\\";

            _pck = new ExcelPackage();
        }

19 Source : PhotoResizer_ResizeShould.cs
with MIT License
from appsonsf

[TestMethod]
        public void SavedAndSizeIsCorrect()
        {
            var filePath = "..\\..\\..\\Inputreplacedets\\IMG_2301.jpg";
            var saveFilePath = Path.Combine(Path.GetTempPath(), "IMG_2301.jpg");
            using (var load = new FileStream(filePath, FileMode.Open))
            {
                var image = SystemDrawingImage.FromStream(load, false, false);
                load.Position = 0;
                using (var save = new FileStream(saveFilePath, FileMode.Create))
                {
                    PhotoResizer.Resize(load, save, image.Width, image.Height);
                }
            }

            replacedert.IsTrue(File.Exists(saveFilePath));
            using (var fs = new FileStream(saveFilePath, FileMode.Open))
            {
                replacedert.IsTrue(fs.Length > 0);
                var image = SystemDrawingImage.FromStream(fs, false, false);
                replacedert.IsTrue(image.Width == PhotoResizer.DefaultThumbnailSize
                    || image.Height == PhotoResizer.DefaultThumbnailSize);
            }
        }

19 Source : ContextMenuFunctions.cs
with MIT License
from Arefu

public static void ViewImage(ListViewItem Item)
        {
            var RandFileName = new Random(DateTime.Now.Millisecond).Next();
            ExtractFile(Item, $"{Path.GetTempPath()}\\{RandFileName}");
            var Viewer = new ImageViewer($"{Path.GetTempPath()}\\{RandFileName}");
            Viewer.ShowDialog();
        }

19 Source : Disk_loader.cs
with GNU Affero General Public License v3.0
from arklumpus

public static TreeCollection Load(Avalonia.Controls.Window parentWindow, FileInfo fileInfo, string filetypeModuleId, IEnumerable<TreeNode> treeLoader, List<(string, Dictionary<string, object>)> moduleSuggestions, ref Action<double> openerProgressAction, Action<double> progressAction)
        {
            long largeFileThreshold = 26214400;

            if (TreeViewer.GlobalSettings.Settings.AdditionalSettings.TryGetValue("Large file threshold:", out object largeFileThresholdValue))
            {
                if (largeFileThresholdValue is long threshValue)
				{
					largeFileThreshold = threshValue;
				}
				else if (largeFileThresholdValue is JsonElement element)
				{
					largeFileThreshold = element.GetInt64();
				}
            }

            if (treeLoader is TreeCollection coll)
            {
                openerProgressAction = (val) => { progressAction(val); };

                if (coll[0].Children.Count > 2)
                {
                    if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                    {
                        moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                    }
                }

                return coll;
            }
            else
            {
                if (fileInfo.Length > largeFileThreshold)
                {
                    bool result = false;
                    int skip = 0;
                    int every = 1;
                    int until = -1;

                    if (InstanceStateData.IsUIAvailable)
                    {
                        EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);

                        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                        {
                            Window settingsWindow = new Window() { Width = 450, Height = 300, FontFamily = Avalonia.Media.FontFamily.Parse("resm:TreeViewer.Fonts.?replacedembly=TreeViewer#Open Sans"), FontSize = 15, replacedle = "Skip trees...", WindowStartupLocation = WindowStartupLocation.CenterOwner };

                            Grid mainGrid = new Grid() { Margin = new Avalonia.Thickness(10) };
                            mainGrid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                            mainGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

                            settingsWindow.Content = mainGrid;

                            StackPanel panel = new StackPanel();
                            mainGrid.Children.Add(panel);


                            Grid alertPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                            alertPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            alertPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            alertPanel.Children.Add(MainWindow.GetAlertIcon());
                            TextBlock alertBlock = new TextBlock() { Text = "The file you are trying to open is very large (" + (fileInfo.Length / 1024 / 1024).ToString() + "MB). The trees are going to be read from the disk, so there should not be any memory issues; however, the input file needs to be converted to a binary format: to speed things up, you may want to skip some of the trees.", TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Avalonia.Thickness(5, 0, 0, 0) };

                            Grid.SetColumn(alertBlock, 1);
                            alertPanel.Children.Add(alertBlock);
                            panel.Children.Add(alertPanel);

                            Grid skipPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                            skipPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            skipPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            skipPanel.Children.Add(new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = "Trees to skip:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                            NumericUpDown skipNud = new NumericUpDown() { Minimum = 0, FormatString = "0", Value = 0, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                            Grid.SetColumn(skipNud, 1);
                            skipPanel.Children.Add(skipNud);
                            panel.Children.Add(skipPanel);

                            Grid everyPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                            everyPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            everyPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            everyPanel.Children.Add(new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = "Sample a tree every:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                            NumericUpDown everyNud = new NumericUpDown() { Minimum = 1, FormatString = "0", Value = 1, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                            Grid.SetColumn(everyNud, 1);
                            everyPanel.Children.Add(everyNud);
                            panel.Children.Add(everyPanel);

                            Grid untilPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                            untilPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            untilPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            CheckBox untilBox = new CheckBox() { FontWeight = Avalonia.Media.FontWeight.Bold, Content = "Up to tree:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                            untilPanel.Children.Add(untilBox);
                            NumericUpDown untilNud = new NumericUpDown() { Minimum = 1, FormatString = "0", Value = 1, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                            Grid.SetColumn(untilNud, 1);
                            untilPanel.Children.Add(untilNud);
                            panel.Children.Add(untilPanel);

                            Grid buttonPanel = new Grid();
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            Button okButton = new Button() { Width = 100, Content = "OK" };
                            Grid.SetColumn(okButton, 1);
                            buttonPanel.Children.Add(okButton);
                            Button cancelButton = new Button() { Width = 100, Content = "Cancel" };
                            Grid.SetColumn(cancelButton, 3);
                            buttonPanel.Children.Add(cancelButton);
                            Grid.SetRow(buttonPanel, 1);
                            mainGrid.Children.Add(buttonPanel);


                            okButton.Click += (s, e) =>
                            {
                                result = true;
                                settingsWindow.Close();
                            };

                            cancelButton.Click += (s, e) =>
                            {
                                result = false;
                                settingsWindow.Close();
                            };

                            await settingsWindow.ShowDialog2(parentWindow);

                            skip = (int)Math.Round(skipNud.Value);
                            every = (int)Math.Round(everyNud.Value);
                            if (untilBox.IsChecked == true)
                            {
                                until = (int)Math.Round(untilNud.Value);
                            }

                            handle.Set();
                        });

                        handle.WaitOne();
                    }
                    else
                    {
                        result = true;
                    }

                    if (!result)
                    {
                        if (treeLoader is IDisposable disposable)
                        {
                            disposable.Dispose();
                        }

                        return null;
                    }
                    else
                    {
                        string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

                        using (FileStream fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
                        {
                            if (until == -1)
                            {
                                openerProgressAction = (val) => { progressAction(val); };

                                BinaryTree.WriteAllTrees(treeLoader.Skip(skip).Where((item, index) => index % every == 0), fs);
                            }
                            else
                            {
                                openerProgressAction = (_) => { };

                                double totalTrees = (until - skip) / every;

                                BinaryTree.WriteAllTrees(treeLoader.Take(until).Skip(skip).Where((item, index) => index % every == 0), fs, false, (count) =>
                                {
                                    double progress = Math.Max(0, Math.Min(1, count / totalTrees));
                                    progressAction(progress);
                                });
                            }
                        }

                        FileStream readerFs = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read);

                        TreeCollection tbr = new TreeCollection(readerFs) { TemporaryFile = tempFile };

                        if (tbr[0].Children.Count > 2)
                        {
                            if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                            {
                                moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                            }
                        }

                        if (treeLoader is IDisposable disposable)
                        {
                            disposable.Dispose();
                        }

                        return tbr;
                    }
                }
                else
                {
                    openerProgressAction = (val) => { progressAction(val); };

                    string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

                    using (FileStream fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
                    {
                        BinaryTree.WriteAllTrees(treeLoader, fs);
                    }

                    FileStream readerFs = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                    TreeCollection tbr = new TreeCollection(readerFs) { TemporaryFile = tempFile };

                    if (tbr[0].Children.Count > 2)
                    {
                        if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                        {
                            moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                        }
                    }

                    if (treeLoader is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }

                    return tbr;
                }
            }
        }

19 Source : Attachments.cs
with GNU Affero General Public License v3.0
from arklumpus

public static AttachmentFontFamily Create(string attachmentName, Stream ttfStream)
        {
            string temp = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));

            using (FileStream fs = new FileStream(temp, FileMode.Create))
            {
                ttfStream.CopyTo(fs);
            }

            AttachmentFontFamily tbr = new AttachmentFontFamily(attachmentName, temp);

            try
            {
                ((ClreplacedicDesktopStyleApplicationLifetime)Application.Current.ApplicationLifetime).Exit += (s, e) =>
                {
                    try
                    {
                        tbr.TrueTypeFile.Destroy();
                        File.Delete(temp);
                    }
                    catch
                    {
                    
                    }
                };
            }
            catch
            {

            }

            return tbr;
        }

19 Source : Paste_tree.cs
with GNU Affero General Public License v3.0
from arklumpus

public static async Task PerformAction(int index, MainWindow window)
        {
            string text = await Avalonia.Application.Current.Clipboard.GetTextAsync();

            string tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString("N"));

            System.IO.File.WriteAllText(tempFile, text);

            await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () => { await window.LoadFile(tempFile, true); });
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from arklumpus

private static List<string> ExportCurrentlyOpenTrees()
        {
            List<string> treeFiles = new List<string>();

            foreach (MainWindow window in GlobalSettings.Settings.MainWindows)
            {
                if (window.Trees != null && window.Trees.Count > 0)
                {
                    string targetFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".bin");

                    try
                    {
                        using (System.IO.FileStream fs = new System.IO.FileStream(targetFile, System.IO.FileMode.Create))
                        {
                            string tempFile = System.IO.Path.GetTempFileName();
                            using (System.IO.FileStream ms = new System.IO.FileStream(tempFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                            {
                                using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms, System.Text.Encoding.UTF8, true))
                                {
                                    bw.Write((byte)0);
                                    bw.Write((byte)0);
                                    bw.Write((byte)0);
                                    bw.Write("#TreeViewer");
                                    bw.Write(window.SerializeAllModules(MainWindow.ModuleTarget.AllModules, true));

                                    bw.Write("#Attachments");
                                    bw.Write(window.StateData.Attachments.Count);

                                    foreach (KeyValuePair<string, Attachment> kvp in window.StateData.Attachments)
                                    {
                                        bw.Write(kvp.Key);
                                        bw.Write(2);
                                        bw.Write(kvp.Value.StoreInMemory);
                                        bw.Write(kvp.Value.CacheResults);
                                        bw.Write(kvp.Value.StreamLength);
                                        bw.Flush();

                                        kvp.Value.WriteToStream(ms);
                                    }

                                    bw.Flush();
                                    bw.Write(ms.Position - 3);
                                }

                                ms.Seek(0, System.IO.SeekOrigin.Begin);

                                PhyloTree.Formats.BinaryTree.WriteAllTrees(window.Trees, fs, additionalDataToCopy: ms);
                            }

                            System.IO.File.Delete(tempFile);
                        }

                        treeFiles.Add(targetFile);
                    }
                    catch
                    {

                    }
                }
            }

            return treeFiles;
        }

19 Source : FileExtensions.cs
with GNU Affero General Public License v3.0
from arklumpus

private static void replacedociateExtensionsLinux(IEnumerable<(string, string)> extensions)
        {
            string xml = "<?xml version=\"1.0\"?>\n<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>\n";

            foreach ((string extension, string comment) in extensions)
            {
                string type = "application";
                string mimetype = type + "/vnd.treeviewer." + comment.Replace("file", "").Replace(" ", "").ToLower() + "." + extension;

                xml += "\t<mime-type type=\"" + mimetype + "\">\n\t\t<comment>" + comment + "</comment>\n\t\t<glob pattern=\"*." + extension + "\"/>\n\t</mime-type>\n";
            }

            xml += "</mime-info>\n";

            string temp = Path.Combine(Path.GetTempPath(), "TreeViewer.xml");

            File.WriteAllText(temp, xml);

            foreach ((string extension, string comment) in extensions)
            {
                string iconPath = Path.Combine(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), "Icons");
                string iconFile;

                if (File.Exists(Path.Combine(iconPath, extension + "-16.png")))
                {
                    iconFile = Path.Combine(iconPath, extension);
                }
                else
                {
                    iconFile = Path.Combine(iconPath, "tree");
                }

                string[] sizes = new string[] { "16", "32", "48", "64", "256", "512" };

                string type = "application";
                string mimetype = type + "/vnd.treeviewer." + comment.Replace("file", "").Replace(" ", "").ToLower() + "." + extension;

                for (int i = 0; i < sizes.Length; i++)
                {
                    string currIcon = iconFile + "-" + sizes[i] + ".png";

                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo("xdg-icon-resource");
                    info.ArgumentList.Add("install");
                    info.ArgumentList.Add("--novendor");
                    info.ArgumentList.Add("--context");
                    info.ArgumentList.Add("mimetypes");
                    info.ArgumentList.Add("--size");
                    info.ArgumentList.Add(sizes[i]);
                    info.ArgumentList.Add(currIcon);
                    info.ArgumentList.Add(mimetype.Replace("/", "-"));

                    System.Diagnostics.Process proc = System.Diagnostics.Process.Start(info);

                    proc.WaitForExit();
                }
            }

            System.Diagnostics.ProcessStartInfo mimeInstall = new System.Diagnostics.ProcessStartInfo("xdg-mime");
            mimeInstall.ArgumentList.Add("install");
            mimeInstall.ArgumentList.Add("--novendor");
            mimeInstall.ArgumentList.Add(temp);

            System.Diagnostics.Process mimeInstallProc = System.Diagnostics.Process.Start(mimeInstall);

            mimeInstallProc.WaitForExit();

            System.Diagnostics.ProcessStartInfo mimeDefault = new System.Diagnostics.ProcessStartInfo("xdg-mime");
            mimeDefault.ArgumentList.Add("default");
            mimeDefault.ArgumentList.Add("io.github.arklumpus.TreeViewer.desktop");

            foreach ((string extension, string comment) in extensions)
            {
                string type = "application";
                string mimetype = type + "/vnd.treeviewer." + comment.Replace("file", "").Replace(" ", "").ToLower() + "." + extension;
                mimeDefault.ArgumentList.Add(mimetype);
            }

            System.Diagnostics.Process mimeDefaultProc = System.Diagnostics.Process.Start(mimeDefault);

            mimeDefaultProc.WaitForExit();

            File.Delete(temp);
        }

19 Source : ModuleRepositoryWindow.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus

internal async Task OpenSourceCodeWindow()
        {
            int tabInd = bar.SelectedIndex;
            if (string.IsNullOrEmpty(selectedModules[tabInd]))
            {
                return;
            }

            string moduleId = selectedModules[tabInd];
            string moduleVersion = repositoryModuleHeaders[moduleId].Version.ToString();


            ProgressWindow progressWindow = new ProgressWindow() { ProgressText = "Accessing module database..." };
            _ = progressWindow.ShowDialog2(this);

            ModuleMetadata module;

            try
            {
                Uri moduleFile = new Uri(ModuleRepositoryBaseUri, moduleId + "/" + moduleId + ".v" + moduleVersion + ".json.zip");

                using (WebClient client = new WebClient())
                {
                    string tempFile = Path.GetTempFileName();
                    await client.DownloadFileTaskAsync(moduleFile, tempFile);

                    string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

                    ZipFile.ExtractToDirectory(tempFile, tempDir);

                    File.Delete(tempFile);

                    using (FileStream fs = new FileStream(Path.Combine(tempDir, "Module.json"), FileMode.Open))
                    {
                        module = await System.Text.Json.JsonSerializer.DeserializeAsync<ModuleMetadata>(fs, Modules.DefaultSerializationOptions);
                    }

                    File.Delete(tempFile);
                    Directory.Delete(tempDir, true);
                }
                progressWindow.Close();
            }
            catch (Exception ex)
            {
                progressWindow.Close();
                await new MessageBox("Attention!", "An error occurred while downloading the module file!\n" + ex.Message).ShowDialog2(this);
                return;
            }

            CodeViewerWindow window = new CodeViewerWindow();
            await window.Initialize(module.SourceCode);
            await window.ShowDialog2(this);
        }

19 Source : WelcomeWindow.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus

private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);

            try
            {
                string localDownloadFile = null;

                if (Modules.IsWindows)
                {
                    localDownloadFile = Path.Combine(Path.GetTempPath(), "TreeViewer-Win-x64.msi");
                }
                else if (Modules.IsLinux)
                {
                    localDownloadFile = Path.Combine(Path.GetTempPath(), "TreeViewer-Linux-x64.run");
                }
                else if (Modules.IsMac)
                {
                    localDownloadFile = Path.Combine(Path.GetTempPath(), "TreeViewer-Mac-x64.pkg");
                }

                if (File.Exists(localDownloadFile))
                {
                    File.Delete(localDownloadFile);
                }
            }
            catch { }

            this.FindControl<Button>("CancelButton").Click += (s, e) =>
            {
                this.Close();
            };

            this.FindControl<Button>("OKButton").Click += async (s, e) =>
            {
                if (this.FindControl<RadioButton>("AllModulesRadio").IsChecked == true)
                {
                    ProgressWindow progressWindow = new ProgressWindow() { ProgressText = "Accessing module database..." };
                    _ = progressWindow.ShowDialog2(this);

                    try
                    {
                        Uri moduleHeaderInfo = new Uri(new Uri(GlobalSettings.Settings.ModuleRepositoryBaseUri), "modules.json.gz");

                        List<ModuleHeader> moduleHeaders;

                        Directory.CreateDirectory(Modules.ModulePath);
                        Directory.CreateDirectory(Path.Combine(Modules.ModulePath, "replacedets"));
                        Directory.CreateDirectory(Path.Combine(Modules.ModulePath, "libraries"));
                        File.WriteAllText(Modules.ModuleListPath, "[]");
                        await Modules.LoadInstalledModules(true, null);

                        using (WebClient client = new WebClient())
                        {
                            string tempFile = Path.GetTempFileName();
                            await client.DownloadFileTaskAsync(moduleHeaderInfo, tempFile);

                            using (FileStream fs = new FileStream(tempFile, FileMode.Open))
                            {
                                using (GZipStream decompressionStream = new GZipStream(fs, CompressionMode.Decompress))
                                {
                                    moduleHeaders = await System.Text.Json.JsonSerializer.DeserializeAsync<List<ModuleHeader>>(decompressionStream, Modules.DefaultSerializationOptions);
                                }
                            }

                            File.Delete(tempFile);
                        }

                        progressWindow.IsIndeterminate = false;
                        progressWindow.ProgressText = "Downloading and installing modules...";
                        progressWindow.Progress = 0;


                        for (int i = 0; i < moduleHeaders.Count; i++)
                        {
                            ModuleHeader header = moduleHeaders[i];

                            if (this.FindControl<RadioButton>("AllModulesRadio").IsChecked == true || RecommendedModules.Contains(header.Id))
                            {

                                Uri moduleFile = new Uri(new Uri(GlobalSettings.Settings.ModuleRepositoryBaseUri), header.Id + "/" + header.Id + ".v" + header.Version.ToString() + ".json.zip");

                                using (WebClient client = new WebClient())
                                {
                                    string tempFile = Path.GetTempFileName();
                                    await client.DownloadFileTaskAsync(moduleFile, tempFile);

                                    try
                                    {
                                        ModuleMetadata.Install(tempFile, false, true);
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox message = new MessageBox("Attention", "An error occurred while installing module " + header.Name + "!\n" + ex.Message, MessageBox.MessageBoxButtonTypes.OK);
                                        await message.ShowDialog2(this);
                                    }

                                    File.Delete(tempFile);
                                }
                            }

                            progressWindow.Progress = (double)(i + 1) / moduleHeaders.Count;
                        }

                        progressWindow.Close();

                        if (!Modules.IsMac)
                        {
                            if (Modules.FileTypeModules.Count > 0)
                            {
                                FilereplacedociationWindow filereplacedociationWindow = new FilereplacedociationWindow(new string[] { "False" });
                                filereplacedociationWindow.Show();
                            }
                            else
                            {
                                MainWindow mainWindow = new MainWindow();
                                mainWindow.Show();
                            }
                        }
                        else
                        {
                            MacOSPermissionWindow window = new MacOSPermissionWindow();
                            window.Show();
                        }

                        this.Close();
                    }
                    catch (Exception ex)
                    {
                        progressWindow.Close();

                        MessageBox message = new MessageBox("Attention", "An error occurred while accessing the module database!!\n" + ex.Message, MessageBox.MessageBoxButtonTypes.OK);
                        await message.ShowDialog2(this);
                    }
                }
                else if (this.FindControl<RadioButton>("NoModulesRadio").IsChecked == true)
                {
                    MessageBox message = new MessageBox("Attention", "Please make sure to install the required modules using the Module manager window before using the program!\nYou can open again this window by starting TreeViewer with the \"--welcome\" command-line option.\nAre you sure you want to proceed with this route?", MessageBox.MessageBoxButtonTypes.YesNo);
                    await message.ShowDialog2(this);
                    if (message.Result == MessageBox.Results.Yes)
                    {
                        Directory.CreateDirectory(Modules.ModulePath);
                        Directory.CreateDirectory(Path.Combine(Modules.ModulePath, "replacedets"));
                        Directory.CreateDirectory(Path.Combine(Modules.ModulePath, "libraries"));
                        File.WriteAllText(Modules.ModuleListPath, "[]");
                        await Modules.LoadInstalledModules(true, null);

                        if (!Modules.IsMac)
                        {
                            if (Modules.FileTypeModules.Count > 0)
                            {
                                FilereplacedociationWindow filereplacedociationWindow = new FilereplacedociationWindow(new string[] { "False" });
                                filereplacedociationWindow.Show();
                            }
                            else
                            {
                                MainWindow mainWindow = new MainWindow();
                                mainWindow.Show();
                            }
                        }
                        else
                        {
                            MacOSPermissionWindow window = new MacOSPermissionWindow();
                            window.Show();
                        }

                        this.Close();
                    }
                }
            };
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from arklumpus

private static List<string> ExportAllModules(bool fetchreplacedets)
        {
            List<string> moduleFiles = new List<string>();

            foreach (KeyValuePair<string, ModuleMetadata> kvp in Modules.LoadedModulesMetadata)
            {
                if (kvp.Value.IsInstalled)
                {
                    string modulePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), kvp.Key + ".json.zip");
                    kvp.Value.Export(modulePath, true, true, fetchreplacedets);
                    moduleFiles.Add(modulePath);
                }
            }

            return moduleFiles;
        }

19 Source : ModuleRepositoryWindow.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus

private async void InstallClicked()
        {
            int tabInd = bar.SelectedIndex;
            if (string.IsNullOrEmpty(selectedModules[tabInd]))
            {
                await new MessageBox("Attention!", "No module has been selected!").ShowDialog2(this);
                return;
            }

            string moduleId = selectedModules[tabInd];


            Uri moduleFile = new Uri(ModuleRepositoryBaseUri, moduleId + "/" + moduleId + ".v" + repositoryModuleHeaders[moduleId].Version.ToString() + ".json.zip");

            string tempFile = Path.GetTempFileName();

            ProgressWindow progressWindow = new ProgressWindow() { ProgressText = "Downloading module file..." };
            _ = progressWindow.ShowDialog2(this);

            try
            {
                using (WebClient client = new WebClient())
                {
                    await client.DownloadFileTaskAsync(moduleFile, tempFile);
                }

                progressWindow.Close();
            }
            catch (Exception ex)
            {
                progressWindow.Close();
                await new MessageBox("Attention!", "An error occurred while downloading the module file!\n" + ex.Message).ShowDialog2(this);
                return;
            }

            string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            bool keepModuleFile = false;
            try
            {
                ZipFile.ExtractToDirectory(tempFile, tempDir);

                ModuleMetadata metaData;

                using (FileStream fs = new FileStream(Path.Combine(tempDir, "Module.json"), FileMode.Open))
                {
                    metaData = await System.Text.Json.JsonSerializer.DeserializeAsync<ModuleMetadata>(fs, Modules.DefaultSerializationOptions);
                }

                if (Modules.LoadedModulesMetadata.ContainsKey(metaData.Id))
                {
                    bool installUnsigned = false;

                    if (!metaData.VerifySignature())
                    {
                        MessageBox box = new MessageBox("Attention", "The source code of the module could not be verified. Proceed only if you trust the source from which you obtained the module. Do you wish to proceed?", MessageBox.MessageBoxButtonTypes.YesNo);
                        await box.ShowDialog2(this);
                        if (box.Result != MessageBox.Results.Yes)
                        {
                            return;
                        }
                        else
                        {
                            installUnsigned = true;
                        }
                    }

                    {
                        MessageBox box = new MessageBox("Question", "A previous version of the same module is already installed. We will now uninstall the previous version and install the current version.\nThe program will be rebooted in the process (we will do our best to recover the files that are currently open). Do you wish to proceed?", MessageBox.MessageBoxButtonTypes.YesNo, MessageBox.MessageBoxIconTypes.QuestionMark);
                        await box.ShowDialog2(this);
                        if (box.Result != MessageBox.Results.Yes)
                        {
                            return;
                        }
                    }

                    bool copyReferences = false;

                    if (metaData.AdditionalReferences.Length > 0)
                    {
                        MessageBox box = new MessageBox("Question", "Do you want to install the external reference files as well?", MessageBox.MessageBoxButtonTypes.YesNo, MessageBox.MessageBoxIconTypes.QuestionMark);
                        await box.ShowDialog2(this);
                        copyReferences = box.Result == MessageBox.Results.Yes;
                    }

                    try
                    {
                        ModuleMetadata.Uninstall(metaData.Id);
                    }
                    catch (Exception ex)
                    {
                        await new MessageBox("Attention!", "An error occurred while uninstalling the previous version of the module!\n" + ex.Message).ShowDialog2(this);
                    }

                    await new MessageBox("Success!", "The previous version of the module was successfully uninstalled! The program will now reboot.\nPlease be patient for a few seconds...", iconType: MessageBox.MessageBoxIconTypes.Tick).ShowDialog2(this);

                    keepModuleFile = true;

                    List<string> newArgs = new List<string>()
                    {
                        "-i", tempFile, "-b", "--delete-modules"
                    };

                    if (installUnsigned)
                    {
                        newArgs.Add("--install-unsigned");
                    }

                    if (copyReferences)
                    {
                        newArgs.Add("--install-references");
                    }

                    Program.Reboot(newArgs.ToArray(), true);
                    ((IClreplacedicDesktopStyleApplicationLifetime)Application.Current.ApplicationLifetime).Shutdown(0);
                }
                else
                {
                    if (!metaData.VerifySignature())
                    {
                        MessageBox box = new MessageBox("Attention", "The source code of the module could not be verified. Proceed only if you trust the source from which you obtained the module. Do you wish to proceed?", MessageBox.MessageBoxButtonTypes.YesNo);
                        await box.ShowDialog2(this);
                        if (box.Result != MessageBox.Results.Yes)
                        {
                            return;
                        }
                    }

                    metaData.IsInstalled = true;

                    Modules.LoadModule(metaData);

                    managerWindowParent.BuildModuleButton(new KeyValuePair<string, ModuleMetadata>(metaData.Id, metaData));
                    repositoryModuleHeaders.Remove(moduleId);
                    ((IPanel)ModuleButtons[moduleId].Item2.Parent).Children.Remove(ModuleButtons[moduleId].Item2);
                    ModuleButtons.Remove(moduleId);
                    noModuleGrids[tabInd].IsVisible = true;

                    foreach (KeyValuePair<string, ModuleHeader> module in repositoryModuleHeaders)
                    {
                        if ((int)module.Value.ModuleType == tabInd)
                        {
                            progressWindow = new ProgressWindow() { ProgressText = "Downloading module file..." };
                            _ = progressWindow.ShowDialog2(this);

                            await SelectModule(module.Key, module.Value.Version.ToString());

                            progressWindow.Close();
                            break;
                        }
                    }

                    notifications = new NotificationType[headers.Length];

                    foreach (ModuleHeader header in repositoryModuleHeaders.Values)
                    {
                        bool newModule = !Modules.LoadedModulesMetadata.TryGetValue(header.Id, out ModuleMetadata loadedModuleMetadata);

                        if (newModule || loadedModuleMetadata.Version < header.Version)
                        {
                            if (newModule)
                            {
                                notifications[(int)header.ModuleType] |= NotificationType.NewModules;
                            }
                            else
                            {
                                notifications[(int)header.ModuleType] |= NotificationType.Updates;
                            }
                        }
                    }

                    for (int i = 0; i < headers.Length; i++)
                    {
                        switch (notifications[i])
                        {
                            case NotificationType.None:
                                notificationEllipses[i].Clreplacedes.Remove("Updates");
                                notificationEllipses[i].Clreplacedes.Remove("NewModules");
                                break;
                            case NotificationType.Updates:
                                notificationEllipses[i].Clreplacedes.Add("Updates");
                                notificationEllipses[i].Clreplacedes.Remove("NewModules");
                                break;
                            case NotificationType.NewModules:
                                notificationEllipses[i].Clreplacedes.Remove("Updates");
                                notificationEllipses[i].Clreplacedes.Add("NewModules");
                                break;
                            case NotificationType.Both:
                                notificationEllipses[i].Clreplacedes.Add("Updates");
                                notificationEllipses[i].Clreplacedes.Add("NewModules");
                                break;
                        }
                    }

                    bool copyReferences = false;

                    if (metaData.AdditionalReferences.Length > 0)
                    {
                        MessageBox box = new MessageBox("Question", "Do you want to install the external reference files as well?", MessageBox.MessageBoxButtonTypes.YesNo, MessageBox.MessageBoxIconTypes.QuestionMark);
                        await box.ShowDialog2(this);
                        copyReferences = box.Result == MessageBox.Results.Yes;
                    }

                    string newModuleDLL = Path.Combine(tempDir, Guid.NewGuid().ToString());

                    using (FileStream fs = new FileStream(newModuleDLL, FileMode.Create))
                    {
                        metaData.Build(fs);
                    }

                    string newModuleList = Path.Combine(tempDir, Guid.NewGuid().ToString());

                    using (FileStream fs = new FileStream(newModuleList, FileMode.Create))
                    {
                        System.Text.Json.JsonSerializer.Serialize(new System.Text.Json.Utf8JsonWriter(fs), from el in Modules.LoadedModulesMetadata where el.Value.IsInstalled == true select el.Value, typeof(IEnumerable<ModuleMetadata>), Modules.DefaultSerializationOptions);
                    }

                    List<string> filesToCopy = new List<string>();
                    filesToCopy.Add(Path.GetFullPath(newModuleList));
                    filesToCopy.Add(Path.GetFullPath(Modules.ModuleListPath));
                    filesToCopy.Add(Path.GetFullPath(newModuleDLL));
                    filesToCopy.Add(Path.GetFullPath(Path.Combine(Modules.ModulePath, metaData.Id + ".dll")));

                    if (copyReferences)
                    {
                        for (int i = 0; i < metaData.AdditionalReferences.Length; i++)
                        {
                            string actualPath = Path.Combine(tempDir, Path.GetFileName(metaData.AdditionalReferences[i]));

                            if (File.Exists(actualPath))
                            {
                                filesToCopy.Add(Path.GetFullPath(actualPath));
                                filesToCopy.Add(Path.GetFullPath(Path.Combine(Modules.ModulePath, "libraries", Path.GetFileName(actualPath))));
                            }
                        }
                    }

                    if (Directory.Exists(Path.Combine(tempDir, "replacedets")))
                    {
                        foreach (string file in Directory.GetFiles(Path.Combine(tempDir, "replacedets"), "*.*"))
                        {
                            filesToCopy.Add(Path.GetFullPath(file));
                            filesToCopy.Add(Path.GetFullPath(Path.Combine(Modules.ModulePath, "replacedets", metaData.Id + "_" + Path.GetFileName(file))));
                        }
                    }

                    for (int i = 0; i < filesToCopy.Count; i += 2)
                    {
                        File.Copy(filesToCopy[i], filesToCopy[i + 1], true);
                    }


                    await new MessageBox("Success!", "Module installed succesfully!", MessageBox.MessageBoxButtonTypes.OK, MessageBox.MessageBoxIconTypes.Tick).ShowDialog2(this);
                }
            }
            catch (Exception ex)
            {
                await new MessageBox("Attention!", "An error occurred while installing the module!\n" + ex.Message).ShowDialog2(this);
            }
            finally
            {
                if (!keepModuleFile)
                {
                    try
                    {
                        File.Delete(tempFile);
                    }
                    catch { }
                }

                try
                {
                    Directory.Delete(tempDir, true);
                }
                catch { }
            }
        }

See More Examples