C#: Implementation of, or alternative to, StrCmpLogicalW in shlwapi.dll

后端 未结 4 1410
一整个雨季
一整个雨季 2020-12-01 17:04

For natural sorting in my application I currently P/Invoke a function called StrCmpLogicalW in shlwapi.dll. I was thinking about trying to run my application under Mono, but

4条回答
  •  没有蜡笔的小新
    2020-12-01 17:46

    If you're running on Windows XP or newer, you can PInvoke to the shell function StrCmpLogicalW:

    public static int StrCmpLogical(String s1, String s2)
    {
        if (String.IsNullOrEmpty(s1) && !String.IsNullOrEmpty(s2))
            return 1; //empty s1 comes after s2
        else if (String.IsNullOrEmpty(s2) && !String.IsNullOrEmpty(s1))
            return -1; //non-empty string comes before empty
    
        return SafeNativeMethods.StrCmpLogicalW(s1, s2);
    }
    

    And then the internal unsafe class:

    /// 
    /// This class suppresses stack walks for unmanaged code permission. 
    /// (System.Security.SuppressUnmanagedCodeSecurityAttribute is applied to this class.) 
    /// This class is for methods that are safe for anyone to call. 
    /// Callers of these methods are not required to perform a full security review to make sure that the 
    /// usage is secure because the methods are harmless for any caller.
    /// 
    [SuppressUnmanagedCodeSecurity]
    internal static class SafeNativeMethods
    {
        [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
        internal static extern Int32 StrCmpLogicalW(string psz1, string psz2);
    }
    

提交回复
热议问题