我想使用COM Api或WMI更改共享文件夹中的“启用基于访问的枚举”,“允许共享缓存”和“加密数据访问”属性.
我以前使用Win32_Share创建共享,但是没有属性来分配这些属性.
但后来我开始了解’MSFT_SmbShare’类,但我只能看到CreateShare方法.我是在退出共享时启用/禁用这些标志但无法找到任何UpdateShare方法.
请建议一种方法,通过COM API或WMI中的任何一个在共享上切换这些标志.
解决方法
要更改这些设置,您可以使用Windows SDK中可用的级别为1005的
NetShareSetInfo function.
此处定义了所有标志,但请注意,文档未显示SHI1005_FLAGS_ENCRYPT_DATA(0x08000),它确实位于相应的Windows头文件LMERR.H中.
这是一个演示如何在C#控制台应用程序中使用它的示例:
class Program { static void Main(string[] args) { // get flags of "myshare" share var flags = NetShareUtilities.Get1005Flags(null,"myshare"); // add the "Require encryption" flag flags |= SHI1005_FLAGS.SHI1005_FLAGS_ENCRYPT_DATA; // save flags (you'll need to have admin rights for this) NetShareUtilities.Set1005Flags(null,"myshare",flags); } }
以下是使用P / Invoke访问Windows API的NetShareUtilities类:
public static class NetShareUtilities { [DllImport("netapi32.dll")] private extern static int NetShareSetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername,[MarshalAs(UnmanagedType.LPWStr)] string netname,int level,ref SHI1005_FLAGS buf,IntPtr parm_err); [DllImport("netapi32.dll")] private extern static int NetShareGetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername,out IntPtr bufptr); [DllImport("netapi32.dll")] private static extern IntPtr NetApiBufferFree(IntPtr Buffer); public static SHI1005_FLAGS Get1005Flags(string serverName,string name) { IntPtr ptr; int err = NetShareGetInfo(serverName,name,1005,out ptr); if (err != 0) throw new Win32Exception(err); var flags = (SHI1005_FLAGS)Marshal.ReadInt32(ptr); NetApiBufferFree(ptr); return flags; } public static void Set1005Flags(string serverName,string name,SHI1005_FLAGS flags) { // note: you need to have enough rights to call this int err = NetShareSetInfo(serverName,ref flags,IntPtr.Zero); if (err != 0) throw new Win32Exception(err); } } [Flags] public enum SHI1005_FLAGS { // note: all values are taken from LMERR.H SHI1005_FLAGS_DFS = 0x0001,SHI1005_FLAGS_DFS_ROOT = 0x0002,// these 3 ones are not strict flags,you'll need to use a mask as specified in the official documentation CSC_CACHE_AUTO_REINT = 0x0010,CSC_CACHE_VDO = 0x0020,CSC_CACHE_NONE = 0x0030,SHI1005_FLAGS_RESTRICT_EXCLUSIVE_OPENS = 0x00100,SHI1005_FLAGS_FORCE_SHARED_DELETE = 0x00200,SHI1005_FLAGS_ALLOW_NAMESPACE_CACHING = 0x00400,SHI1005_FLAGS_ACCESS_BASED_DIRECTORY_ENUM = 0x00800,SHI1005_FLAGS_FORCE_LEVELII_OPLOCK = 0x01000,SHI1005_FLAGS_ENABLE_HASH = 0x02000,SHI1005_FLAGS_ENABLE_CA = 0x04000,SHI1005_FLAGS_ENCRYPT_DATA = 0x08000,SHI1005_FLAGS_RESERVED = 0x10000,}