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);
        }

    }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.