10 July, 2012
0 Comments
1 category
I wanted to save information found in a file to a database without having to deal with encodings, well I found my solution at
http://stackoverflow.com/questions/472906/net-string-to-byte-array-c-sharp
[TestClass] public class RliResearchTester { [TestMethod] public void Test() { string input = "Hèllo world"; byte[] inputBytes = GetBytes(input); string output = GetString(inputBytes); Assert.AreEqual(input, output); } public byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } public string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } }
Tags: C#
Category: Uncategorized