0

我目前正在编写的应用程序有一个奇怪的问题。我很确定我最近没有更改以下代码中的任何内容,但不知何故它停止了工作。说到点子上了。我正在使用:

[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern uint NetShareGetInfo(
        string servername,
        string netname,
        int level,
        out IntPtr ppBuf
        );

导入NetApi32.dll。我需要物理路径。无法使用 WMI 和 WinRM。 然后我有如下枚举和结构:

public enum ShType
    {
        DiskTree = 0,
        PrintQ = 1,
        Device = 2,
        IPC = 3,
        Temporary = 0x40000000,
        Special = unchecked((int)0x80000000)
    }
    public struct SHARE_INFO_502
    {
        public string Name;
        public ShType Type;
        public string Remark;
        public int Permissions;
        public int MaxUses;
        public int CurrentUses;
        public string Path;
        public string PassWd;
        public int reserved;
        public IntPtr SecDescriptor;
    }

全部在

 [SuppressUnmanagedCodeSecurity]
public static class SafeNativeMethods

根据 VS 代码分析器进行分类。我称之为:

 IntPtr ptrGet;
 var resGetInfo = SafeNativeMethods.NetShareGetInfo("server_name", "share_name", 502, out ptrGet);             
 SafeNativeMethods.SHARE_INFO_502 siGet = (SafeNativeMethods.SHARE_INFO_502)Marshal.PtrToStructure(ptrGet, typeof(SafeNativeMethods.SHARE_INFO_502));

运行上述代码后,我没有收到任何错误或异常,但是,siGet Struct 只有每个属性值的第一个字母。问题可能出在哪里?

4

1 回答 1

1

默认字符集是Ansi,这就是结构编组使用的。但是您选择了该函数的 Unicode 版本。您还应该为结构指定字符集:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHARE_INFO_502
....

编组文本时的一些提示:

  • 每当您只看到字符串的第一个字符时,您首先应该怀疑您将 UTF-16 文本解释为 ANSI 或 UTF-8。
  • 每当您在预期的英语中看到看起来像中文的文本时,您首先应该怀疑您将 ANSI 或 UTF-8 文本解释为 UTF-16。
于 2017-06-30T11:38:45.107 回答