111,131
社区成员
发帖
与我相关
我的任务
分享
FileStream fs = new FileStream(@"C:\test.dat", FileMode.Open, FileAccess.Read);
int numBytesToRead = (int)fs.Length;
int numBytesReaded = 0;
while (numBytesToRead > 0)
{
byte[] intBytes = new byte[4];
int n = fs.Read(intBytes, numBytesReaded, 4);
numBytesReaded += n;
numBytesToRead -= n;
if (n == 0)
{
break;
}
int value = BitConverter.ToInt32(intBytes, 0);//get the int value
byte[] charBytes = new byte[60];
n = fs.Read(intBytes, numBytesReaded, 60);
if (n == 0)
{
break;
}
string valueStr = BitConverter.ToString(charBytes, 0);//get the string value
numBytesReaded += n;
numBytesToRead -= n;
}
byte[] rawBytes = System.IO.File.ReadAllBytes(@"my.dat");
int i = BitConverter.ToInt32(rawBytes, 0);
string s = Encoding.Default.GetString(rawBytes, 4, 60); //or ASCII encoding, according to your impelmentation
FileStream fs = new FileStream(@"C:\test",FileMode.Open,FileAccess.ReadWrite);
int value = 265;
byte[] bytesInt = BitConverter.GetBytes(value);
fs.Write(bytesInt, 0, 4);
char[] valueStr = ("这次是测试").ToCharArray();
byte[] bytes = new byte[60];
byte[] strBytes = Encoding.Unicode.GetBytes(valueStr, 0, valueStr.Length);
for (int i = 0; i < 60; i++)
{
if (i < strBytes.Length)
{
bytes[i] = strBytes[i];
}else
{
bytes[i] = 0;//'\0'
}
}
fs.Write(bytes, 0, 60);
//保存文件
fs.Flush();
fs.Close();