none
converting array list to byte array +C#

    General discussion



  •                    while converting arraylist to byte array ..it shows an exception called invalid cast exception ..how can i overcome it.and convert arraylist to byte array....in C#..
    Regards,
    ALGATES
    Tuesday, January 29, 2008 6:23 AM

All replies

  • Does the ArrayList contain only byte elements? Can you post your code?

     

     

    Tuesday, January 29, 2008 9:29 AM
  • I had a similar question, and yes, in my case I had only byte elements.  The issue was reading in a file of unknown number of byte elements, so I couldn't just write it to bytes directly:

    ASCIIEncoding ByteConverter = new ASCIIEncoding();
    
    List<byte> byteList = new List<byte>();
    
    FileStream fs = new FileStream(@"C:\test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    BinaryReader br = new BinaryReader(fs); 
    
    byte[] bytesToDecrypt = ByteConverter.GetBytes("z");
    
    while (bytesToDecrypt != null)
    {
      byteList.Add = br.ReadByte();
    }
    
    br.Close();
    fs.Close();
    
    foreach (byte b in byteList)
    {
      bytesToDecrypt. // stuck here
    
    }

    Any help is appreciated.

     

    Thanks, Tom 

     

     

    • Edited by navyjax2 Wednesday, July 21, 2010 6:35 PM
    Wednesday, July 21, 2010 12:39 PM
  • Turned out I didn't have to turn the byte[] into a list<byte> after all. What I was trying to do was to read base64 into a string, and what I did was convert the bytes to characters and added them into a string.

    byte[] base64encryptedbytes = Program.ReadByteArrayFromFile("test.txt"); 
    string base64text = ""; 
    foreach (byte b in base64encryptedbytes) { 
    if (((char)b).ToString() != "\0") 
    base64text += (char)b; 
    } 

    This works awesome and functions as a base64 string. Can even get the bytes again with:

     byte[] getTheBytes = Convert.FromBase64String(base64text); 

    -Tom

    Wednesday, July 21, 2010 6:31 PM
  • Here's the "ReadByteArrayFromFile" function, in case anyone wants it:

        public static byte[] ReadByteArrayFromFile(string fileName)
        {
          byte[] buff = null;
          FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
          BinaryReader br = new BinaryReader(fs);
          long numBytes = new FileInfo(fileName).Length;
          buff = br.ReadBytes((int)numBytes);
          return buff;
        }
    
    -Tom
    Wednesday, July 21, 2010 6:37 PM