判斷一個軟件,是否以及被外部打開過

軟件已經被外部佔用或者打開 爲1 ,沒有打開過,爲0

namespace Co獲取打開某一文件的軟件名稱
{
    class Program
    {
        static void Main(string[] args)
        {




            string str2 = FileAssociation.FileExtentionInfo(FileAssociation.AssocStr.FriendlyAppName, @".pdf",null);
            Console.WriteLine(str2);


            //C:\Users\Software\Desktop\EappdXml.pdf;
           //string testFilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"testOpen.txt";
            
            
            
            string testFilePath = @"D:\CloudCompare_v2.10.alpha_bin_x64\CloudCompare.exe";
            
            FileStream fs = new FileStream(testFilePath, FileMode.OpenOrCreate, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            int result = -1;
            br.Read();
           // Console.WriteLine("文件被打開");
          // result = FileStatus.FileIsOpen(testFilePath);
           // Console.WriteLine(result);
            br.Close();
           
            Console.WriteLine("文件被關閉");
            result = FileStatus.FileIsOpen(testFilePath);
            Console.WriteLine(result);
            Console.ReadLine();

        }
        public static class FileStatus
        {
            [DllImport("kernel32.dll")]
            private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
            [DllImport("kernel32.dll")]
            private static extern bool CloseHandle(IntPtr hObject);
            private const int OF_READWRITE = 2;
            private const int OF_SHARE_DENY_NONE = 0x40;
            private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
            public static int FileIsOpen(string fileFullName)
            {
                if (!File.Exists(fileFullName))
                {
                    return -1;
                }
                IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);
                if (handle == HFILE_ERROR)
                {
                    return 1;
                }
                CloseHandle(handle);
                return 0;
            }
        }
      
        /// <summary>
        /// Usage:  string executablePath = FileAssociation.GetExecFileAssociatedToExtension(pathExtension, "open");
        /// </summary>
        public static class FileAssociation
        {

            public static string FileExtentionInfo2(AssocStr assocStr, string doctype)
            {
                if ((doctype.Length <= 1) || !doctype.StartsWith(".")) return "";

                uint pcchOut = 0;
                AssocQueryString(AssocF.Verify, assocStr, doctype, null, null, ref pcchOut);

                if (pcchOut == 0) return (doctype.Trim('.').ToUpper() + " File");

                StringBuilder pszOut = new StringBuilder((int)pcchOut);
                AssocQueryString(AssocF.Verify, assocStr, doctype, null, pszOut, ref pcchOut);
                return pszOut.ToString();
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="ext"></param>
            /// <param name="verb"></param>
            /// <returns>Return null if not found</returns>
            public static string GetExecFileAssociatedToExtension(string ext, string verb = null)
            {
                if (ext[0] != '.')
                {
                    ext = "." + ext;
                }

                string executablePath = FileExtentionInfo(AssocStr.Executable, ext, verb); // Will only work for 'open' verb
                if (string.IsNullOrEmpty(executablePath))
                {
                    executablePath = FileExtentionInfo(AssocStr.Command, ext, verb); // required to find command of any other verb than 'open'

                    // Extract only the path
                    if (!string.IsNullOrEmpty(executablePath) && executablePath.Length > 1)
                    {
                        if (executablePath[0] == '"')
                        {
                            executablePath = executablePath.Split('\"')[1];
                        }
                        else if (executablePath[0] == '\'')
                        {
                            executablePath = executablePath.Split('\'')[1];
                        }
                    }
                }

                // Ensure to not return the default OpenWith.exe associated executable in Windows 8 or higher
                if (!string.IsNullOrEmpty(executablePath) && File.Exists(executablePath) &&
                    !executablePath.ToLower().EndsWith(".dll"))
                {
                    if (executablePath.ToLower().EndsWith("openwith.exe"))
                    {
                        return null; // 'OpenWith.exe' is th windows 8 or higher default for unknown extensions. I don't want to have it as associted file
                    }
                    return executablePath;
                }
                return executablePath;
            }

            [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
            static extern uint AssocQueryString(AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, [In][Out] ref uint pcchOut);

            public static string FileExtentionInfo(AssocStr assocStr, string doctype, string verb)
            {
                uint pcchOut = 0;
                AssocQueryString(AssocF.Verify, assocStr, doctype, verb, null, ref pcchOut);

                Debug.Assert(pcchOut != 0);
                if (pcchOut == 0)
                {
                    return "";
                }

                StringBuilder pszOut = new StringBuilder((int)pcchOut);
                AssocQueryString(AssocF.Verify, assocStr, doctype, verb, pszOut, ref pcchOut);
                return pszOut.ToString();
            }

            [Flags]
            public enum AssocF
            {
                Init_NoRemapCLSID = 0x1,
                Init_ByExeName = 0x2,
                Open_ByExeName = 0x2,
                Init_DefaultToStar = 0x4,
                Init_DefaultToFolder = 0x8,
                NoUserSettings = 0x10,
                NoTruncate = 0x20,
                Verify = 0x40,
                RemapRunDll = 0x80,
                NoFixUps = 0x100,
                IgnoreBaseClass = 0x200
            }

            public enum AssocStr
            {
                Command = 1,
                Executable,
                FriendlyDocName,
                FriendlyAppName,
                NoOpen,
                ShellNewValue,
                DDECommand,
                DDEIfExec,
                DDEApplication,
                DDETopic
            }

        }

    }
}


以上也是翻出來找來的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章