user1016179 user1016179 - 9 days ago 6
C# Question

How to convert Char[] or String to Char* for initialize SecureString in C#?

I'm trying to initialize SecureString and I need Char* for that.
I tried to do it with block of unsafe code:

unsafe {
char[] c = { 'A', 'B', 'C', 'D' };
char* pointer = &(c[0]);
SecureString sec = new SecureString(pointer, 4);
}


When try this I got this error:


Error: You can only take the address of an unfixed expression inside
of a fixed statement initializer

Answer

Why not just loop through each char and use AppendChar?

string s = "Hello";
SecureString ss = new SecureString();

foreach(char c in s) ss.AppendChar(c);