Search code examples
c#.netvisual-studiowinformswinforms-to-web

How to get the program's current folder name and extract the zip file to the current folder in C#?


I have a Winforms Auto Updater.

If I open the program it will get the file download link from a raw text which contains the .zip file download link to the program from the web.

But if the person made a folder and put the program in the folder I want the program to get the folder name the program is in and extract the zip file to it.

Here's my code:

private void StartDownload()
        {
            WebClient webClient = new WebClient();
            string path = "./Sympathy";
            string address1 = "https://ghostbin.co/paste/cjx7j/raw";
            string address2 = webClient.DownloadString(address1);
            this.progressBar1.Value = 100;
            string str = "./Sympathy.zip";
            if (System.IO.File.Exists(str))
            {
                System.IO.File.Delete(str);
            }
            else
            {
                webClient.DownloadFile(address2, str);
                ZipFile.ExtractToDirectory(str, Directory.GetCurrentDirectory(Directory).Name); 
                System.IO.File.Delete(str);
            }
        }

But I'm having an error on the (Directory) part, How do I fix it?


Solution

  • To get the path to your executable use System.Reflection.Assembly.GetEntryAssembly().Location;, to get the directory use Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

    I see that your code is flawed. Use this instead, to do everything :

    string archivePath = "Sympathy.zip";
    using (var client = new WebClient())
    {
        client.DownloadFile(client.DownloadString("https://ghostbin.co/paste/cjx7j/raw"), archivePath);
        ZipFile.ExtractToDirectory(archivePath, Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));
        File.Delete(archivePath);
    }
    

    It works. It downloads a bunch of unknown files.