C#向数组添加数据?

C#向数组添加数据?,c#,arrays,C#,Arrays,下面的代码读取文件偏移量并将十六进制值写入“MyGlobals.Hexbytes”变量。。。。如何让它改为写入数组 非常感谢 MyGlobals.Mapsettings_filepath = "C:\\123.cfg"; ///////////////////////////// Read in the selected ////////////// BinaryReader br = new BinaryReader(File.OpenRead(MyGlobals.Mapsettings_

下面的代码读取文件偏移量并将十六进制值写入“MyGlobals.Hexbytes”变量。。。。如何让它改为写入数组

非常感谢

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") + ",";
}
MyGlobals.Mapsettings\u filepath=“C:\\123.cfg”;
/////////////////////////////读入所选内容//////////////
BinaryReader br=新的BinaryReader(File.OpenRead(MyGlobals.Mapsettings\u filepath),
System.Text.Encoding.BigEndianUnicode);

对于(int a=32;aMake
MyGlobals.Hexbytes
List
,则:

br.BaseStream.Position = a;
MyGlobals.Hexbytes.Add(br.ReadByte().ToString("X2"));
稍后要显示它,请使用
String.Join
如下所示:

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

数组是固定大小的结构,因此不能向其中添加元素

如果您事先知道大小(如示例中所示),则可以实例化它,然后将元素添加到预先分配的插槽中:

e、 g

string[]byteStrings=新字符串[5];//36-32+1=5

对于(int a=32;a您应该首先定义数组的大小,因此您应该首先设置其大小,然后填充它:

string[] array = new string[5];

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

假设
MyGlobals.Hexbytes
,很可能,您可以让代码保持原样,并在最后添加以下内容:

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

myarray
是一个字符串数组。

很难说你想要什么。你想更改
MyGlobals.Hexbytes
?你想要什么类型的数组?一个字节数组,一个字符串数组,等等?请编辑你的问题以添加此信息。谢谢你的回答…还有没有其他方法我可以读取4字节而不是一个byt每次?@user,有什么区别?@user826436,我用代码更新了我的答案,用binaryreader读取了4个字节
string[] array = new string[5];

for (int a = 32; a <= 36; a++)
{
    br.BaseStream.Position = a;
    array[a - 32] += br.ReadByte().ToString("X2");
}
            BinaryReader reader = ....;
...
            byte[] buffer = new byte[4];
            reader.Read(buffer, 0, 4);

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