本文整理汇总了C#中System.Security.Principal.NTAccount.Translate方法的典型用法代码示例。如果您正苦于以下问题:C# NTAccount.Translate方法的具体用法?C# NTAccount.Translate怎么用?C# NTAccount.Translate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Principal.NTAccount
的用法示例。
在下文中一共展示了NTAccount.Translate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MainWindow
// Constructor //
public MainWindow()
{
InitializeComponent();
// Get user name
this.username = Environment.UserName.ToString();
// Get user SID
NTAccount acct = new NTAccount(username);
SecurityIdentifier s = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
this.usrSID = s.ToString();
// Get user home directory
this.homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
// Get volume location (default)
this.defaultVolumeLoc = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)) + this.username + ".hc";
// Figure out where the home folder's encrypted file is located for this user //
string encDrive = (string)Registry.GetValue(Config.LOCAL_MACHINE_REG_ROOT + this.usrSID, "encDrive", string.Empty);
string encContainerLoc = (string)Registry.GetValue(Config.LOCAL_MACHINE_REG_ROOT + this.usrSID, "encContainerLoc", string.Empty);
if (!string.IsNullOrWhiteSpace(encContainerLoc) && !string.IsNullOrWhiteSpace(encDrive) && Directory.Exists(encDrive + @":\"))
{
// We're already running in an encrypted home directory environment!
g_tabContainer.Controls[0].Enabled = false;
l_homeAlreadyEncrypted.Visible = true;
l_homeAlreadyEncrypted.Enabled = true;
}
// * //
l_statusLabel.Text = "Ready ...";
Application.DoEvents();
}
示例2: DeleteUserProfile
/// <summary>
/// Deletes the user profile.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">The domain name of the user to act as.</param>
public static void DeleteUserProfile(string userName, string domainName)
{
NTAccount ntaccount = new NTAccount(domainName, userName);
string userSid = ntaccount.Translate(typeof(SecurityIdentifier)).Value;
bool retry = true;
int retries = 2;
while (retry && retries > 0)
{
retry = false;
if (!DeleteProfile(userSid, null, null))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == 2)
{
// Error Code 2: The user profile was not created or was already deleted
return;
}
else if (errorCode == 87)
{
// Error Code 87: The user profile is still loaded.
retry = true;
retries--;
}
else
{
throw new Win32Exception(errorCode);
}
}
}
}
示例3: GetUncPathForDrive
public string GetUncPathForDrive(string domain, string user, string drive)
{
var userIdentifier = String.Format(@"{0}\{1}", domain, user);
if (!driveCache.ContainsKey(userIdentifier))
{
var account = new NTAccount(domain, user);
if (account == null)
return null;
var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
if (sid == null)
return null;
var drives = RegistryReader.GetSubKeys(RegistryHive.Users, RegistryView.Default, String.Format(@"{0}\Network", sid.Value));
if (drives == null)
return null;
driveCache[userIdentifier] = drives.Select(driveLetter => {
string uncPath = RegistryReader.ReadKey(RegistryHive.Users, RegistryView.Default, String.Format(@"{0}\Network\{1}", sid.Value, driveLetter), "RemotePath").ToString();
return new KeyValuePair<string, string>(driveLetter, uncPath);
}).Where(x => x.Value != null).ToDictionary();
}
if (driveCache[userIdentifier].ContainsKey(drive))
return driveCache[userIdentifier][drive];
return null;
}
示例4: btnOK_Click
private void btnOK_Click(object sender, EventArgs e)
{
bool success = false;
try
{
Sid = new SecurityIdentifier(textBoxSid.Text);
success = true;
}
catch (Exception)
{
}
if (!success)
{
try
{
NTAccount acct = new NTAccount(textBoxSid.Text);
Sid = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
success = true;
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
if (success)
{
DialogResult = DialogResult.OK;
Close();
}
}
示例5: Execute
public void Execute()
{
PrintHeader();
var id = WindowsIdentity.GetCurrent();
Console.WriteLine("Identity Id: " + id.Name);
var account = new NTAccount(id.Name);
var sid = account.Translate(typeof(SecurityIdentifier));
Console.WriteLine("SecurityIdentifier (sid): " + sid.Value);
foreach (var group in id.Groups.Translate(typeof(NTAccount)))
Console.WriteLine("InGroup: " + group);
var principal = new WindowsPrincipal(id);
var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
Console.WriteLine("IsInRole(localAdmin): " + principal.IsInRole(localAdmins));
var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
Console.WriteLine("IsInRole(domainAdmin): " + principal.IsInRole(domainAdmins));
Console.WriteLine();
// be aware for desktop/local accounts User Account Control (UAC from Vista) strips user of admin rights,
// unless the process was run elevated "as Admin".
}
示例6: GetSidFromClaim
public static SecurityIdentifier GetSidFromClaim(string claimValue)
{
SecurityIdentifier sid = null;
SPClaimProviderManager claimManager = SPClaimProviderManager.Local;
if (claimManager == null)
{
throw new ApplicationException("Unable to access the claims provider manager.");
}
try
{
SPClaim claim = claimManager.DecodeClaim(claimValue);
if (claim.OriginalIssuer.Equals("Windows", StringComparison.OrdinalIgnoreCase))
{
if (claim.ClaimType.Equals(Microsoft.IdentityModel.Claims.ClaimTypes.GroupSid, StringComparison.OrdinalIgnoreCase))
{
sid = new SecurityIdentifier(claim.Value);
}
else if (claim.ClaimType.Equals(Microsoft.SharePoint.Administration.Claims.SPClaimTypes.UserLogonName, StringComparison.OrdinalIgnoreCase))
{
NTAccount userAccount = new NTAccount(claim.Value);
sid = (SecurityIdentifier)userAccount.Translate(typeof(SecurityIdentifier));
}
}
}
catch (ArgumentException currentException)
{
GlymaSearchLogger.WriteTrace(LogCategoryId.Security, TraceSeverity.Unexpected, "The following exception occured when attempting to decode the claim, " + claimValue + " : " + currentException.ToString());
}
return sid;
}
示例7: FindSid
public SidWrapper FindSid(string account)
{
SecurityIdentifier sid = null;
try
{
// first, let's try this as a sid (SDDL) string
sid = new SecurityIdentifier(account);
return new SidWrapper { Sid = sid};
}
catch
{
}
try
{
// maybe it's an account/group name
var name = new NTAccount(account);
sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
if (sid != null)
{
return new SidWrapper { Sid = sid };
}
}
catch
{
}
return null;
}
示例8: AddReservation
/// <summary>
/// Adds a reservation to the list of reserved URLs
/// </summary>
/// <param name="urlPrefix">The prefix of the URL to reserve.</param>
/// <param name="user">The user with which to reserve the URL.</param>
internal static void AddReservation(string urlPrefix, string user)
{
NTAccount account = new NTAccount(user);
SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
string sddl = GenerateSddl(sid);
ErrorCode retVal = ErrorCode.Success; // NOERROR = 0
retVal = NativeMethods.HttpInitialize(HttpApiConstants.Version1, HttpApiConstants.InitializeConfig, IntPtr.Zero);
if (ErrorCode.Success == retVal)
{
HttpServiceConfigUrlAclKey keyDesc = new HttpServiceConfigUrlAclKey(urlPrefix);
HttpServiceConfigUrlAclParam paramDesc = new HttpServiceConfigUrlAclParam(sddl);
HttpServiceConfigUrlAclSet inputConfigInfoSet = new HttpServiceConfigUrlAclSet();
inputConfigInfoSet.KeyDesc = keyDesc;
inputConfigInfoSet.ParamDesc = paramDesc;
IntPtr inputConfigInfoBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(HttpServiceConfigUrlAclSet)));
Marshal.StructureToPtr(inputConfigInfoSet, inputConfigInfoBuffer, false);
retVal = NativeMethods.HttpSetServiceConfiguration(
IntPtr.Zero,
HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
inputConfigInfoBuffer,
Marshal.SizeOf(inputConfigInfoSet),
IntPtr.Zero);
if (ErrorCode.AlreadyExists == retVal)
{
retVal = NativeMethods.HttpDeleteServiceConfiguration(
IntPtr.Zero,
HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
inputConfigInfoBuffer,
Marshal.SizeOf(inputConfigInfoSet),
IntPtr.Zero);
if (ErrorCode.Success == retVal)
{
retVal = NativeMethods.HttpSetServiceConfiguration(
IntPtr.Zero,
HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
inputConfigInfoBuffer,
Marshal.SizeOf(inputConfigInfoSet),
IntPtr.Zero);
}
}
Marshal.FreeHGlobal(inputConfigInfoBuffer);
NativeMethods.HttpTerminate(HttpApiConstants.InitializeConfig, IntPtr.Zero);
}
if (ErrorCode.Success != retVal)
{
throw new Win32Exception(Convert.ToInt32(retVal, CultureInfo.InvariantCulture));
}
}
示例9: GetVMnameSid
public static SecurityIdentifier GetVMnameSid(string VMName)
{
ManagementObjectCollection queryCollection;
SecurityIdentifier sid = null;
try
{
ManagementScope scope = new ManagementScope(@"\\.\root\virtualization\v2");
scope.Connect();
string querystr = "SELECT * FROM Msvm_ComputerSystem where ElementName=\"" + VMName + "\"";
ObjectQuery query = new ObjectQuery(querystr);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
queryCollection = searcher.Get();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
//Console.WriteLine("Name,GUID,PID");
try
{
foreach (ManagementObject vm in queryCollection)
{
try
{
// display VM details
//Console.WriteLine("{0},{1},{2}", vm["ElementName"].ToString(),
// vm["Name"].ToString(), vm["ProcessID"].ToString());
string concat = "NT VIRTUAL MACHINE\\" + vm["Name"].ToString();
NTAccount ntaccount = new NTAccount(concat);
sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier));
Console.WriteLine("{0},{1},{2},{3}", vm["ElementName"].ToString(),
vm["Name"].ToString(), vm["ProcessID"].ToString(), sid.ToString());
}
catch (Exception /*e*/)
{
// don't print anything, some entries might miss fields like process id, ignore and move on
//Console.WriteLine(e.ToString());
continue;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
return sid;
}
示例10: GetNoneGroupSID
public static string GetNoneGroupSID()
{
try
{
var objUsersGroup = new NTAccount("None");
return ((SecurityIdentifier)objUsersGroup.Translate(typeof(SecurityIdentifier))).Value;
}
catch
{
throw new Exception("Could not get SID for the local 'None' group. Aborting.");
}
}
示例11: GetCurrentUserSid
internal static string GetCurrentUserSid()
{
try
{
string fullLogin = Environment.UserDomainName + "\\" + Environment.UserName;
var account = new NTAccount(fullLogin);
IdentityReference sidReference = account.Translate(typeof(SecurityIdentifier));
return sidReference.ToString();
}
catch
{
return null;
}
}
示例12: GetSIDFromUsername
/// <summary>
/// Returns the SID of the user with the username
/// Throws an exception of something does not work
/// </summary>
/// <param name="username">Username</param>
/// <returns>SID as String</returns>
public static string GetSIDFromUsername(string username)
{
try
{
var account = new NTAccount(username);
var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
return sid.ToString();
}
catch (Exception ex)
{
Logger.Log(ex, String.Format("Unable to get SID for username {0}",username));
throw;
}
}
示例13: RegSec
/// <summary>
/// apply registry security settings to user profiles
/// </summary>
/// <param name="where"></param>
/// <param name="keyname"></param>
/// <param name="username"></param>
/// <returns></returns>
public static Boolean RegSec(pInvokes.structenums.RegistryLocation where, string keyname, string username)
{
try
{
IdentityReference UserIRef = new NTAccount(String.Format("{0}\\{1}", Environment.MachineName, username));
SecurityIdentifier UserSid = (SecurityIdentifier)UserIRef.Translate(typeof(SecurityIdentifier));
using (RegistryKey key = pInvokes.GetRegistryLocation(where).OpenSubKey(keyname, true))
{
RegistrySecurity keySecurity = key.GetAccessControl(AccessControlSections.Access);
string SDDL = keySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
//LibraryLogging.Info(SDDL);
foreach (RegistryAccessRule user in keySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
//LibraryLogging.Info("registry ACE user: {0} {1} {2}", key.Name, user.InheritanceFlags.ToString(), user.IdentityReference.Value);
if (user.IdentityReference.Value.StartsWith("S-1-5-21-") && !user.IdentityReference.Value.Equals(UserIRef.Value))
{
//LibraryLogging.Info("mod registry ACE:{0} from unknown user:{1} to {2} {3} {4}", key.Name, user.IdentityReference.Value, username, user.RegistryRights.ToString(), user.AccessControlType.ToString());
SDDL = SDDL.Replace(user.IdentityReference.Value, UserSid.Value);
//LibraryLogging.Info(SDDL);
keySecurity.SetSecurityDescriptorSddlForm(SDDL);
key.SetAccessControl(keySecurity);
break;
}
}
foreach (string subkey in key.GetSubKeyNames())
{
if (!RegSec(where, keyname + "\\" + subkey, username))
{
return false;
}
}
}
}
catch (SystemException ex)
{
LibraryLogging.Warn("RegSec:{0} Warning {1}", keyname, ex.Message);
}
catch (Exception ex)
{
LibraryLogging.Error("RegSec:{0} Error:{1}", keyname, ex.Message);
return false;
}
return true;
}
示例14: GetCurrentUserPath
public static string GetCurrentUserPath(string userName)
{
string[] items = userName.Split('\\');
string user = null;
string domain = null;
if (items.Length == 2)
{
user = items[1];
domain = items[0];
}
else
user = items[0];
try
{
NTAccount account = new NTAccount(domain, user);
SecurityIdentifier sid = (SecurityIdentifier) account.Translate(typeof(SecurityIdentifier));
string SID = sid.Value;
string keypath = SID + @"\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders";
RegistryKey shellFolders = Registry.Users.OpenSubKey(keypath);
if (shellFolders != null)
{
string appDataPath = (string) shellFolders.GetValue("AppData", string.Empty);
if (string.IsNullOrEmpty(appDataPath))
return string.Empty;
StringBuilder sb = new StringBuilder(appDataPath);
sb.Append(PolicySetsFolder());
return sb.ToString();
}
}
catch (Exception ex)
{
Logger.LogError("PolicyMonitor: Failed to get the logged on users' sid for " + userName);
Logger.LogError(ex);
}
return string.Empty;
}
示例15: AccountExists
public static bool AccountExists(this String name)
{
bool bRet = false;
try
{
NTAccount acct = new NTAccount(name);
SecurityIdentifier id = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
bRet = id.IsAccountSid();
}
catch (IdentityNotMappedException)
{
/* Invalid user account */
}
return bRet;
}