I'm trying to convert a securestring to a string using the function below. However, the returned string always has one additional character appended which I think is a null. No matter what I do with "nothing", "vbnull", "dbnull" etc. this extra character is always present. I've even tried doing a .Replace on the final string but whatever it is remains.

The only fix I've found is to clip it off using a .Substring, but this is a nasty kludge.

Anyone see what I'm doing wrong?

VB Code:
  1. Public Function SecureStringToString(ByVal str As System.Security.SecureString) As String
  2.         Dim bstr As IntPtr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(str)
  3.         Dim b As Byte = 1
  4.         Dim i As Integer = 0
  5.         Dim s As String = ""
  6.         While Chr(b) <> Chr(0) 'I also tried IsNothing, IsNull, IsDBNull, = vbNull, = Nothing
  7.             b = System.Runtime.InteropServices.Marshal.ReadByte(bstr, i)
  8.             i += 2
  9.             s += Chr(b)
  10.         End While
  11.         s = s.Substring(0, s.Length - 1) 'This line is the kludge
  12.         System.Runtime.InteropServices.Marshal.FreeBSTR(bstr)
  13.         Return s
  14.     End Function