xml地图|网站地图|网站标签 [设为首页] [加入收藏]
并做为参数字传送入泛型方法中动用,将结构体
分类:编程

1、 将基础类型转为byte数组存储

 1  private byte[] CreateNetDataByteStream(ushort system, ushort host, ushort type, byte[] tx_buf, ushort msg_len, ushort flag)
 2 
 3         {
 4 
 5             if (tx_buf == null)
 6 
 7             {
 8 
 9                 return null;
10 
11             }
12 
13             try
14 
15             {
16 
17                 byte[] data = new byte[msg_len + NetDataHeadLen];
18 
19                 byte[] u16byte = new byte[2];
20 
21                 u16byte = BitConverter.GetBytes(type);
22 
23                 Array.Copy(u16byte, 0, data, 0, 2);
24 
25                 u16byte = BitConverter.GetBytes(flag);
26 
27                 Array.Copy(u16byte, 0, data, 4, 2);
28 
29                 u16byte = BitConverter.GetBytes(msg_len);
30 
31                 Array.Copy(u16byte, 0, data, 2, 2);
32 
33                // u16byte = BitConverter.GetBytes(CommonConstant.MySystemID);
34 
35                 Array.Copy(u16byte, 0, data, 6, 2);
36 
37               //  u16byte = BitConverter.GetBytes((ushort)CommonConstant.MySeatName);
38 
39                 Array.Copy(u16byte, 0, data, 8, 2);
40 
41                 u16byte = BitConverter.GetBytes(system);
42 
43                 Array.Copy(u16byte, 0, data, 15, 2);
44 
45                 u16byte = BitConverter.GetBytes(host);
46 
47                 Array.Copy(u16byte, 0, data, 17, 2);
48 
49                 tx_buf.CopyTo(data, NetDataHeadLen);
50 
51                 return data;
52 
53             }
54 
55             catch
56 
57             {
58                 return null;
59 
60             }
61 
62         }

2.C#中结构体 与 字节流 相互转化

       

方式一
        //将一个结构序列化为字节数组
               private IFormatter formatter = new BinaryFormatter();
        private ValueType deserializeByteArrayToInfoObj(byte[] bytes)
        {
            ValueType vt;
            if (bytes == null || bytes.Length == 0)
            {
                return null;
            }

            try
            {
                MemoryStream stream = new MemoryStream(bytes);
                stream.Position = 0;
                stream.Seek(0, SeekOrigin.Begin);
                vt = (ValueType)formatter.Deserialize(stream);
                stream.Close();
                return vt;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        //将一个结构序列化为字节数组
        private byte[] serializeInfoObjToByteArray(ValueType infoStruct)
        {
            if (infoStruct == null)
            {
                return null;
            }

            try
            {
                MemoryStream stream = new MemoryStream();
                formatter.Serialize(stream, infoStruct);

                byte[] bytes = new byte[(int)stream.Length];
                stream.Position = 0;
                int count = stream.Read(bytes, 0, (int)stream.Length);
                stream.Close();
                return bytes;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

方式二
   /// <summary>
        /// 将字节数组转换为结构体
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public object ByteaToStruct(byte[] bytes, Type type)
        {
            //得到结构体大小
            int size = Marshal.SizeOf(type);
            Math.Log(size, 1);

            if (size > bytes.Length)
                return null;
            //分配结构大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将BYTE数组拷贝到分配好的内存空间
            Marshal.Copy(bytes, 0, structPtr, size);
            //将内存空间转换为目标结构
            object obj = Marshal.PtrToStructure(structPtr, type);
            //释放内容空间
            Marshal.FreeHGlobal(structPtr);
            return obj;
        }
        /// <summary>
        /// 将结构转换为字节数组
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public byte[] StructTOBytes(object obj)
        {
            int size = Marshal.SizeOf(obj);
            //创建byte数组
            byte[] bytes = new byte[size];
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷贝到分配好的内存空间
            Marshal.StructureToPtr(obj, structPtr, false);
            //从内存空间拷贝到byte数组
            Marshal.Copy(structPtr, bytes,0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            return bytes;
        }

3. C# 结构体字节对齐

1 [structLayout(Layoutkind.sequential,charset=charset.ansi)]
2 Struct Mystruct
3 {
4 [MarshalAs(UnmanagedType.ByValArray,sizeConst=8)]
5 Public byte[] serial;
6 Public byte Type;
7 Public uint Sum;
8 }

在上述结构体与字节流转换第二种方法中,获取结构体长度int size = Marshal.SizeOf(Mystruct);,并不是13,而是16。在内存特定类型数据结构起始地址通常有一定的对齐要求,比如32位机器的int起始地址必须是4的整数倍,结构通常也如此

需要添加[structLayout(Layoutkind.sequential,charset=charset.ansi,pack=1)]

工作中有这样一个需求,有N张不同的报表,每张报表对应一个数据源,统计数据采用内存方式,首先在内在里定义了数据源对应实体。统计条件用lamdba表达式式实现,通过工具对单元格进行定义。在实现过程中针对每一张表来写取数显示是很Low的了,取数条件定义都是规则的,统计实现就是一段C#代码,但是要针对不同的数据源也就是不同的List<Entity>,通过研究发现通过泛型和反射可以实现。

如何获取当前系统用户对文件/文件夹的操作权限?

根据字符串获取实体类型

 1.获取安全信息DirectorySecurity

DirectorySecurity fileAcl = Directory.GetAccessControl(folder);

通过Directory.GetAccessControl获取文件夹的权限/安全信息

详细介绍,可参考MSDN官方文档)

对文件/文件夹权限的详细操作,可参考一篇博客C#文件夹权限操作

 1 private Type getEntity(string typeName)
 2 {
 3     var workPath = AppDomain.CurrentDomain.BaseDirectory;
 4     string[] files = Directory.GetFiles(workPath, "XXX.Utils.dll", SearchOption.TopDirectoryOnly);
 5     foreach (string file in files)
 6     {
 7         string ext = file.Substring(file.LastIndexOf("."));
 8         if (ext != ".dll") continue;
 9         try
10         {
11             Assembly asm = Assembly.LoadFile(file);
12             Type[] allTypes = asm.GetTypes();
13             foreach (Type t in allTypes)
14             {
15                 if (t.IsSubclassOf(typeof(XXDataRecord)))
16                 {
17                     if (t.Name.ToUpper().IsSame(typeName.ToUpper()))
18                         return t;
19                 }
20             }
21         }
22         catch
23         {
24             return null;
25         }
26     }
27     return null;
28 }

2. 获取文件夹访问权限列表FileSystemAccessRule

var rules = fileAcl.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)).OfType<FileSystemAccessRule>().ToList();

GetAccessRules()方法返回的是AuthorizationRule集合,此处只需要获取文件权限。

FileSystemAccessRule.aspx)继承自AuthorizationRule,并新增俩个属性

  • AccessControlType -- 枚举 Allow/Deny
  • FileSystemRights -- 对文件的访问权限详细信息(读/写等),可见下面列表: 

澳门新葡亰手机版 1澳门新葡亰手机版 2

 1   /// <summary>定义要创建访问和审核规则时使用的访问权限。</summary>
 2   [Flags]
 3   public enum FileSystemRights
 4   {
 5     ReadData = 1,
 6     ListDirectory = ReadData, // 0x00000001
 7     WriteData = 2,
 8     CreateFiles = WriteData, // 0x00000002
 9     AppendData = 4,
10     CreateDirectories = AppendData, // 0x00000004
11     ReadExtendedAttributes = 8,
12     WriteExtendedAttributes = 16, // 0x00000010
13     ExecuteFile = 32, // 0x00000020
14     Traverse = ExecuteFile, // 0x00000020
15     DeleteSubdirectoriesAndFiles = 64, // 0x00000040
16     ReadAttributes = 128, // 0x00000080
17     WriteAttributes = 256, // 0x00000100
18     Delete = 65536, // 0x00010000
19     ReadPermissions = 131072, // 0x00020000
20     ChangePermissions = 262144, // 0x00040000
21     TakeOwnership = 524288, // 0x00080000
22     Synchronize = 1048576, // 0x00100000
23     FullControl = Synchronize | TakeOwnership | ChangePermissions | ReadPermissions | Delete | WriteAttributes | ReadAttributes | DeleteSubdirectoriesAndFiles | Traverse | WriteExtendedAttributes | ReadExtendedAttributes | CreateDirectories | CreateFiles | ListDirectory, // 0x001F01FF
24     Read = ReadPermissions | ReadAttributes | ReadExtendedAttributes | ListDirectory, // 0x00020089
25     ReadAndExecute = Read | Traverse, // 0x000200A9
26     Write = WriteAttributes | WriteExtendedAttributes | CreateDirectories | CreateFiles, // 0x00000116
27     Modify = Write | ReadAndExecute | Delete, // 0x000301BF
28   }

View Code

 因为AuthorizationRule中,IdentityReference对应权限的用户/用户组标识,格式为:"MYDOMAINMyAccount"

所以,如通过当前系统用户名与IdentityReference匹配,即可获取FileSystemAccessRule权限。如何获取用户名,见下一段落

 

3. 获取当前系统用户名/用户组

通过 System.Environment.UserDomainName 和 System.Environment.UserName 取得当前用户名

对当前系统用户名/用户组的其它操作,可参考

  • C# 管理 Windows 本地用户组
  • C# 获取 Windows 用户组成员

因此,将Path.Combine(Environment.UserDomainName, Environment.UserName)与IdentityReference.Value比较,获取当前用户对文件夹的权限信息

详细实现如下:

 1     /// <summary>
 2     /// 检查当前用户是否拥有此文件夹的操作权限
 3     /// </summary>
 4     /// <param name="folder"></param>
 5     /// <returns></returns>
 6     public static bool HasOperationPermission(string folder)
 7     {
 8         var currentUserIdentity = Path.Combine(Environment.UserDomainName, Environment.UserName);
 9 
10         DirectorySecurity fileAcl = Directory.GetAccessControl(folder);
11         var userAccessRules = fileAcl.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)).OfType<FileSystemAccessRule>().Where(i=>i.IdentityReference.Value==currentUserIdentity).ToList();
12 
13         return userAccessRules.Any(i => i.AccessControlType == AccessControlType.Deny);
14     }

 

泛型方法定义

本文由澳门新葡亰手机版发布于编程,转载请注明出处:并做为参数字传送入泛型方法中动用,将结构体

上一篇:没有了 下一篇:没有了
猜你喜欢
热门排行
精彩图文