Here is an example on how to convert a String to Securestring using C# and VB.NET.
Please remember that the plain string which will be converted to SecureString beats the whole point of using SecureString. This method should only be used for testing purposes.
This Extension Method is now part of the Fesslersoft.Extensions.

Samples

C# Sample

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

VB.NET Sample

<System.Runtime.CompilerServices.Extension> _
Public Shared Function ToSecureString(source As String) As SecureString
	If String.IsNullOrWhiteSpace(source) Then
		Return Nothing
	End If
	Dim result = New SecureString()
	For Each c As char In source
		result.AppendChar(c)
	Next
	Return result
End Function

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

Leave a Reply