initialize byte[] ?


  • I want to initialize a byte[] (array) with some similar to we initialize the string variable
    string s=string.Empty;
    byte[] fileStream = ? ;

    as I want to have a while loop on fileStream.Length but if I don't initialize it with something then it will give me error as "fileStream is unassigned variable".
    Please suggest.

    Thanks!! MCP
    Monday, October 19, 2009 4:06 PM


All replies

  • The issue with arrays is that you have to know the size of the array in order to initialize it.  Once you know the size of the array (it's length), then initializing it is as simple as this:

    byte[] fileStream = new byte[length];

    where "length" is a variable holding the length of the byte array. 

    If you simply need an empty array, try:

    byte[] fileStream = new byte[0];
    Coding Light - Illuminated Ideas and Algorithms in Software
    Coding Light WikiLinkedInForumsBrowser
    • Marked as answer by GurunGuns Tuesday, October 20, 2009 12:16 AM
    Monday, October 19, 2009 4:16 PM
  • A byte[] is not a file stream.  I'm guessing you are actually looking for this:

      fs = new FileStream(...);
      int len = (int)fs.Length;
      byte[] buffer = new byte[len];
      fs.Read(buffer, 0, len);

    Same as File.ReadAllBytes().

    Hans Passant.
    Monday, October 19, 2009 10:12 PM