简体   繁体   中英

How to determine if C# executable is being run from zip file?

I'm trying to ensure that users of my C# .NET Core program always unzip it before running, however, I can't seem to find a good solution for this.

I tried using Assembly.GetExecutingAssembly().Location and checking if it contained Temp but it did not work as intended. My understanding is that when running an executable within a zipped file, Windows will automatically unzip (?) to a temp directory and then proceed.

Any ideas on how to go about doing this?

Thanks!

One solution might be that you put another file beside the exe file inside the zip file and make the exe find for this file in the same location of the exe.

When an exe is executed from inside a zip, the unzip program will unzip the exe but not the other file and checking for this file you can test whether just the exe was unzziped or if the whole files where unzipped and the guess it was installed.

(Anyway, I agree with Ian Kemp, as it seems to be an XY problem)..

I can think of two checks that will work in many cases. Obviously, these checks are not bullet-proof.

  1. Most .zip viewers will extract the clicked .exe in a temporary folder.
  2. Windows Explorer zip folder view runs the .exe from a temporary folder and sets the ReadOnly attribute.

Sample app

using System;
using System.IO;

namespace SimpleApp
{
    class Program
    {
        private static bool IsLikelyRunFromZipFolder()
        {
            var path = System.Reflection.Assembly.GetEntryAssembly().Location;
            var fileInfo = new FileInfo(path);
            return fileInfo.Attributes.HasFlag(FileAttributes.ReadOnly);
        }

        private static bool IsRunFromTempFolder()
        {
            var path = System.Reflection.Assembly.GetEntryAssembly().Location;
            var temp = Path.GetTempPath();
            return path.IndexOf(temp, StringComparison.OrdinalIgnoreCase) == 0;
        }

        static void Main(string[] args)
        {
            var isTemp = IsRunFromTempFolder();
            var isZip = IsLikelyRunFromZipFolder();
            
            Console.WriteLine($"Run from TEMP folder? {isTemp}");
            Console.WriteLine($"LIKELY run from Windows Explorer ZIP folder? {isZip}");
            
            Console.ReadKey();
        }
    }
}

I disagree with the sceptics in this thread. Running an exe from a "zip folder" in Windows Explorer is indeed a common source of error. By showing a warning, inexperienced users could get some immediate advice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM