Here is an example on how to convert a Securestring to String using C# and VB.NET.
Please remember that storing the data in a plain string will be beat 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 string ToUnsecureString(this SecureString source)
{
	var returnValue = IntPtr.Zero;
	try
	{
		returnValue = Marshal.SecureStringToGlobalAllocUnicode(source);
		return Marshal.PtrToStringUni(returnValue);
	}
	finally
	{
		Marshal.ZeroFreeGlobalAllocUnicode(returnValue);
	}
}

VB.NET Sample

<System.Runtime.CompilerServices.Extension> _
Public Shared Function ToUnsecureString(source As SecureString) As String
	Dim returnValue = IntPtr.Zero
	Try
		returnValue = Marshal.SecureStringToGlobalAllocUnicode(source)
		Return Marshal.PtrToStringUni(returnValue)
	Finally
		Marshal.ZeroFreeGlobalAllocUnicode(returnValue)
	End Try
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