Feedback

Prüfen, ob eine Datei ausfürbar ist (.exe, .bat, etc.)

Sprache: C#

thja… s. den Titel 🙂
    [StructLayout(LayoutKind.Sequential)]
    internal struct SHFILEINFO
    {
        public IntPtr hIcon;
        public IntPtr iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;
    }

        [DllImport("shell32.dll")]
        public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes,
            ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

        /// <summary>
        /// Prüft, ob eine Datei ausfürbar ist (.exe, .bat, etc.)
        /// </summary>
        /// <param name="path">Pfad zu der Datei.</param>
        /// <returns>true, wenn die Datei ausführbar ist, ansonsten false.</returns>
        public static bool IsExecutable(string path)
        {
            SHFILEINFO fi = new SHFILEINFO();
            int SHGFI_EXETYPE = 0x000002000;     // return exe type

            IntPtr res = SHGetFileInfo(
                path,
                0,
                ref fi,
                (uint)System.Runtime.InteropServices.Marshal.SizeOf(fi),
                SHGFI_EXETYPE);

            return (res != IntPtr.Zero);
        }
    [StructLayout(LayoutKind.Sequential)]
    internal struct SHFILEINFO
    {
        public IntPtr hIcon;
        public IntPtr iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;
    }

        [DllImport("shell32.dll")]
        public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes,
            ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

        /// <summary>
        /// Prüft, ob eine Datei ausfürbar ist (.exe, .bat, etc.)
        /// </summary>
        /// <param name="path">Pfad zu der Datei.</param>
        /// <returns>true, wenn die Datei ausführbar ist, ansonsten false.</returns>
        public static bool IsExecutable(string path)
        {
            SHFILEINFO fi = new SHFILEINFO();
            int SHGFI_EXETYPE = 0x000002000;     // return exe type

            IntPtr res = SHGetFileInfo(
                path,
                0,
                ref fi,
                (uint)System.Runtime.InteropServices.Marshal.SizeOf(fi),
                SHGFI_EXETYPE);

            return (res != IntPtr.Zero);
        }

2 Kommentare

  1. @Volker Steitz:

    SHGFI_EXETYPE –
    Retrieve the type of the executable file if pszPath identifies an executable file. The information is packed into the return value. This flag cannot be specified with any other flags.