【发布时间】:2016-06-23 05:16:17
【问题描述】:
目标是将字节数组写入文件。 我有字节数组 fit[] 和一些字节,然后:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace _32_to_16
{
class Program
{
static void Main(string[] args)
{
byte[] fits = File.ReadAllBytes("1.myf");
byte[] img = new byte[fits.Length / 2];
for (int i = 0; i < fits.Length; i += 4) //Drops 2 high bytes
{
img[i/2] = fits[i + 2];
img[i/2 + 1] = fits[i + 3];
}
File.WriteAllBytes("new.myf", img);
}
}
}
在写入文件之前 img[] 具有相同的值:
- img[0]=0x31
- img[1]=0x27
- img[2]=0x31
- img[3]=0xe2
- 等等……
写入文件后,在十六进制编辑器中我看到了
- 00000000: 31 27 31 3f 和其他错误值。
有时,使用其他 fit[] 值,img[] 数组会正确写入文件。我做错了什么?
用于测试 1.myf 的文件(产生错误结果)https://www.dropbox.com/s/6xyf761oqm8j7y1/1.myf?dl=0
用于测试 2.myf 的文件(正确写入文件)https://www.dropbox.com/s/zrglpx7kmpydurz/2.myf?dl=0
我简化了代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace _32_to_16
{
class Program
{
static void Main(string[] args)
{
byte[] img_correct = new byte[8] { 0xbd, 0x19, 0xbd, 0x72, 0xbd, 0x93, 0xbd, 0xf7 };
File.WriteAllBytes("img_correct.myf", img_correct);
byte[] img_strange = new byte[8] { 0x33, 0x08, 0x33, 0xac, 0x33, 0xe3, 0x33, 0x94 };
File.WriteAllBytes("img_strange.myf", img_strange);
}
}
}
在十六进制编辑器 img_correct.myf 中看起来像这样: bd 19 bd 72 bd 93 bd f7
在十六进制编辑器 img_strange.myf 中看起来像这样: 33 08 33 3f 3f 3f
【问题讨论】:
-
你没有吞下异常,是吗?也许文件被锁定并且实际上没有被(覆盖)写入?
-
没有任何例外。没有锁定文件(创建新文件)。我尝试使用 BinaryWriter — 结果相同。 dropbox.com/s/k4zctcy9v2744ke/bw.JPG?dl=0 和 dropbox.com/s/xex5m5gzm2aswnu/notepad%2B%2B.JPG?dl=0
-
嗯,这很奇怪。您可以尝试创建一个minimal reproducible example 以便我们试用吗?
-
我删除了所有额外的代码,只留下了重要的部分。编辑了启动消息。我不知道该去哪里了。
-
调用
WriteAllBytes后,尝试将new.myf文件读入另一个字节数组,然后逐字节比较img与新数组。它们应该是一样的。
标签: c# .net unicode hex-editors