8

I have some C++ code that persists byte values into files via STL strings & text i/o, and am confused about how to do this in C#.

first I convert byte arrays to strings & store each as a row in a text file:

 StreamWriter F
 loop
 {
   byte[] B;       // array of byte values from 0-255 (but never LF,CR or EOF)
   string S = B;   // I'd like to do this assignment in C# (encoding? ugh.) (*)
   F.WriteLine(S); // and store the byte values into a text file
 }

later ... I'd like to reverse the steps and get back the original byte values:

  StreamReader F;   
  loop
  {
    string S = F.ReadLine();   // read that line back from the file
    byte[] B = S;              // I'd like to convert back to byte array (*)
  }

How do you do those assignments (*) ?

2
  • possible duplicate of .NET String to byte Array C# Commented Aug 19, 2013 at 3:54
  • 1
    A little ambiguous... are you wanting to get a text representation of those bytes? IE: byte[] { 0, 1, 2, 3 } becomes "0 1 2 3"? Commented Aug 19, 2013 at 4:06

4 Answers 4

11

class Encoding supports what you need, example below assumes that you need to convert string to byte[] using UTF8 and vice-versa:

string S = Encoding.UTF8.GetString(B);
byte[] B = Encoding.UTF8.GetBytes(S);

If you need to use other encodings, you can change easily:

Encoding.Unicode
Encoding.ASCII
...
Sign up to request clarification or add additional context in comments.

1 Comment

It is also worth noting that System.String stores its data in UTF-16 as the "base format". You can convert that format to any other format in bytes using the proper Encoding as you demonstrated in your answer. :]
2

this one has been answered over and over

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

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


How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

Read the first answer carefully, and the reasons why you would prefer this to the Encoding version.

Comments

1

You can use this code to Convert from string array to Byte and ViseVersa

Click the link to know more about C# byte array to string, and vice-versa

string strText = "SomeTestData";

            //CONVERT STRING TO BYTE ARRAY
            byte[] bytedata = ConvertStringToByte(strText);                              

            //VICE VERSA ** Byte[] To Text **
            if (bytedata  != null)
            {                    
                //BYTE ARRAY TO STRING
                string strPdfText = ConvertByteArrayToString(result);
            }


//Method to Convert Byte[] to string
private static string ConvertByteArrayToString(Byte[] ByteOutput)
{
            string StringOutput = System.Text.Encoding.UTF8.GetString(ByteOutput);
            return StringOutput;
}


//Method to Convert String to Byte[]
public static byte[] ConvertStringToByte(string Input)
{
            return System.Text.Encoding.UTF8.GetBytes(Input);
}

I hope this helps you. Thanks.

Comments

-2
    public Document FileToByteArray(string _FileName)
    {
        byte[] _Buffer = null;

        try
        {
            // Open file for reading
         FileStream _FileStream = new FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            // attach filestream to binary reader
           BinaryReader _BinaryReader = new BinaryReader(_FileStream);
            // get total byte length of the file
            long _TotalBytes = new FileInfo(_FileName).Length;
            // read entire file into buffer
            _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
            // close file reader
            _FileStream.Close();
            _FileStream.Dispose();
            _BinaryReader.Close();
            Document1 = new Document();
            Document1.DocName = _FileName;
            Document1.DocContent = _Buffer;
            return Document1;
        }
        catch (Exception _Exception)
        {
            // Error
            Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        }

        return Document1;
    }

    public void ByteArraytoFile(string _FileName, byte[] _Buffer)
    {
        if (_FileName != null && _FileName.Length > 0 && _Buffer != null)
        {
            if (!Directory.Exists(Path.GetDirectoryName(_FileName)))
                Directory.CreateDirectory(Path.GetDirectoryName(_FileName));

            FileStream file = File.Create(_FileName);

            file.Write(_Buffer, 0, _Buffer.Length);

            file.Close();
        }



    }

public static void Main(string[] args)
    {
        Document doc = new Document();
        doc.FileToByteArray("Path to your file");
        doc.Document1.ByteArraytoFile("path to ..to be created file", doc.Document1.DocContent);
    }
private Document _document;

public Document Document1
{
    get { return _document; }
    set { _document = value; }
}
public int DocId { get; set; }
public string DocName { get; set; }
public byte[] DocContent { get; set; }



}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.