Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将SID字符串格式转换为字节数组_C#_.net_Sid - Fatal编程技术网

C# 将SID字符串格式转换为字节数组

C# 将SID字符串格式转换为字节数组,c#,.net,sid,C#,.net,Sid,我想将SID字符串格式转换为字节数组表示形式,而字节数组表示形式将依次提供给LookupAccountSid()C#中方法的第二个参数。但我没有发现任何特定的内置函数可以做到这一点。例如: SID=S-1-5-32-544 可转换为: (SID:1,2,0,0,0,0,0,5,32,0,0,0,0,32,2,0,0) 我在一些帖子上看到了。但是怎么做呢? 有没有一个简单的方法来实现这一点?基本上,我需要NT Authority\NetworkService的字节数组表示,即SID=S-1-5-2

我想将SID字符串格式转换为字节数组表示形式,而字节数组表示形式将依次提供给
LookupAccountSid()
C#中方法的第二个参数。但我没有发现任何特定的内置函数可以做到这一点。例如:

SID=S-1-5-32-544

可转换为:

(SID:1,2,0,0,0,0,0,5,32,0,0,0,0,32,2,0,0)

我在一些帖子上看到了。但是怎么做呢? 有没有一个简单的方法来实现这一点?基本上,我需要
NT Authority\NetworkService
的字节数组表示,即
SID=S-1-5-20
。提前感谢您的帮助。

您应该使用
System.Security.Principal
命名空间中的对象:

var sid = new SecurityIdentifier("S-1-5-32-544");
byte[] bytes = new byte[sid.BinaryLength];
sid.GetBinaryForm(bytes, 0);
如果您想将其作为文本,则可以:

string strsid = string.Format("(SID: {0})", string.Join(",", bytes ));
这正好产生:

(SID:1,2,0,0,0,0,0,5,32,0,0,0,0,32,2,0,0)

此外,如果您想要NT Authority\NetworkService的SID,可以将第一行替换为:

var sid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);

仅供参考,如果您想转到另一个方向(字节[]到SID),则如下所示。在我的例子中,字节[]来自ManagementEventWatcher:

ManagementBaseObject ne = e.NewEvent;
var securityIdentifier = new System.Security.Principal.SecurityIdentifier((byte[])ne.Properties["SID"].Value, 0);

您可以使用
securityIdentifier.ToString()
将SID作为字符串获取。

LookupAccountSid()
您的代码还是内置函数?除了初始化字节[]外,其他都有