2014-05-22 78 views
1

嗨我有一个xml文件有两个值。如何在c#中使用xml中的字符串变量作为字符串?

的第一个值是PowerShell的 用户名的第二个值是密码作为SecureString的对PowerShell的

现在我想读这个值,并将其设置为变量字符串ps_user和SecureString的ps_password

我问题现在我可以如何使用SecureString值。

这里我的xml:

<?xml version="1.0" encoding="iso-8859-1"?> 

<Credential> 
    <User value="tarasov" /> 
    <SecurePassword value="0d08c9ddf0004800000a0000340b62f9d614" /> 
</Credential> 

这里我的C#代码:

private string GetPowershellCredentials(string path, string attribute) 
     { 
      XDocument document; 
      string value = string.Empty; 

      try 
      { 
       document = XDocument.Load(path); 

       value = document.Element("Credential").Element(attribute).Attribute("value").Value; 

       return value; 
      } 
      catch (Exception) 
      { 
       return null; 
      } 
      finally 
      { 
       document = null; 
      } 
     } 

例如:

> string path = Server.MapPath("~/App_Data/Powershell_credentials.xml"); 

> string ps_user = GetPowershellCredentials(path, "User"); // It works 

> SecureString ps_password = GetPowershellCredentials(path,"SecurePassword"); // this not :((

我怎样才能做到这一点?

回答

1

因为你的GetPowershellCredentials返回一个字符串。这无法自动转换。如果你需要一个安全字符串,你可以使用这样的事情:

public static SecureString ToSecureString(string source) 
{ 
     if (string.IsNullOrWhiteSpace(source)) 
      return null; 
     else 
     { 
      SecureString result = new SecureString(); 
      foreach (char c in source.ToCharArray()) 
       result.AppendChar(c); 
      return result; 
     } 
} 

这:

SecureString ps_password = ToSecureString(GetPowershellCredentials(path, "SecurePassword")); 
+0

但在我的XML值是SecureString的 – Tarasov

+0

您是否尝试过我的解决方案?请试试 –

+0

(Fehler bei SSPI-Aufruf,siehe interne Ausnahme。)in English - > error by SSPI Call,看看实习生Execption ... – Tarasov

相关问题