سؤال

أحاول كتابة فئة C # المدارة لالتفاف shgetnyfolderpath، حتى الآن تعمل على نظام التشغيل Vista، ولكن تعطل على XP بسبب عدم العثور على الوظيفة المناسبة في shell32.dll، كما هو متوقع.

أريد أن أحصل على تحديد ذلك حتى أتمكن من الاسترداد على حل (مخربلة مؤكدا) باستخدام system.environment.getfirderprath إذا كنت تستخدم XP. (أو، حتى أفضل، إذا لم تتمكن من العثور على funciton في shell32.)

هل هناك أي طريقة للقيام بذلك الأخرى ثم مجموعة مشروطة؟

يبدو رمزي الحالي:

public abstract class KnownFolders
    {
        [DllImport("shell32.dll")]
        private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);

        // Trim properties to get various Guids.

        public static string GetKnownFolderPath(Guid guid)
        {
            IntPtr pPath;
            int result = SHGetKnownFolderPath(guid, 0, IntPtr.Zero, out pPath);
            if (result == 0)
            {
                string s = Marshal.PtrToStringUni(pPath);
                Marshal.FreeCoTaskMem(pPath);
                return s;
            }
            else
                throw new System.ComponentModel.Win32Exception(result);
        }
    }
هل كانت مفيدة؟

المحلول

لف مكالمتك إلى shgetlyfolderpath في كتلة المحاولة. أمسك ال system.entrypointnotfoundExcept. ثم جرب الحل البديل الخاص بك:

public static string GetKnownFolderPath(Guid guid)
{
  try
  {
    IntPtr pPath;
    int result = SHGetKnownFolderPath(guid, 0, IntPtr.Zero, out pPath);
    if (result == 0)
    {
        string s = Marshal.PtrToStringUni(pPath);
        Marshal.FreeCoTaskMem(pPath);
        return s;
    }
    else
        throw new System.ComponentModel.Win32Exception(result);
  }
  catch(EntryPointNotFoundException ex)
  {
    DoAlternativeSolution();
  }
}

نصائح أخرى

يمكنك التحقق من إصدار نظام التشغيل باستخدام البيئة خاصية. أعتقد إذا كنت تفعل

int osVersion = Environment.OSVersion.Version.Major

على XP التي ستكون 5، وعلى نظام التشغيل Vista سيكون 6. من هناك فقط لفحص بسيط.

if(osVersion == 5)
{
   //do XP way
}
else if(osVersion == 6)
{
   //P/Invoke it
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top