我如何在x#中使用xml中的字符串作为字符串变量?

时间:2014-05-22 11:30:53

标签: c# asp.net xml powershell securestring

嗨我有一个带有两个值的xml文件。

第一个值是Powershell的用户名 第二个值是powershell

的securestring密码

现在我想读取这些值,并为变量字符串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 个答案:

答案 0 :(得分: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"));