简体   繁体   中英

C# Adding data to an array?

My code below reads a file offset and writes the hexadecimal values to the "MyGlobals.Hexbytes" variable.... How could I get it to write into an array instead?

Many Thanks

MyGlobals.Mapsettings_filepath = "C:\\123.cfg";

///////////////////////////// Read in the selected //////////////

BinaryReader br = new BinaryReader(File.OpenRead(MyGlobals.Mapsettings_filepath),
System.Text.Encoding.BigEndianUnicode);

for (int a = 32; a <= 36; a++)
{
    br.BaseStream.Position = a;
    MyGlobals.Hexbytes += br.ReadByte().ToString("X2") + ",";
}

Make MyGlobals.Hexbytes to be List<string> instead then:

br.BaseStream.Position = a;
MyGlobals.Hexbytes.Add(br.ReadByte().ToString("X2"));

Later to display it, use String.Join like this:

string myBytes = string.Join(",", MyGlobals.Hexbytes.ToArray());

Array is a fixed size structure, so you cannot add elements to it.

If you know the size in advance (as it seems in your example) you can instanciate it and then add elements to the pre-allocated slots:

eg

string[] byteStrings = new string[5]; // 36 - 32 + 1 = 5 

for (int a = 32; a <= 36; a++)
{
   br.BaseStream.Position = a;
   byteStrings[a - 32] = br.ReadByte().ToString("X2");
}

But it's much easier to use a dynamically-resizable collection, like List<T> :

var byteStrings = new List<string>();
for (int a = 32; a <= 36; a++)
{
   br.BaseStream.Position = a;
   byteStrings.Add(br.ReadByte().ToString("X2"));
}

You should first define the size of the array and thus you should first set its size and then populate it:

string[] array = new string[5];

for (int a = 32; a <= 36; a++)
{
    br.BaseStream.Position = a;
    array[a - 32] += br.ReadByte().ToString("X2");
}

Here is how to read 4 bytes at once:

            BinaryReader reader = ....;
...
            byte[] buffer = new byte[4];
            reader.Read(buffer, 0, 4);

...

Assuming MyGlobals.Hexbytes , which is likely, you could leave your code the way it is and add this in the end:

var myarray = MyGlobals.Hexbytes.Split(',');

myarray is an array of string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM