首页 > 解决方案 > 我如何将文件(将 unicode 文本与 00 字节分隔)解析为列表?

问题描述

给定十六进制编辑器中的字节选择显示文件用 00 字节分隔文本,它是一个着色文件,带有材料名称,后跟一个确定颜色的 3 字节十六进制代码。这就是为什么它包含像 FF 这样的字节。字节显示如下:

00 11 46 6F 6C 69 61 67 65 5F 45 76 65 72 67 72 65 65 6E 00 FF FF FF 00 0D 46 6F 6C 69 61 67 65 5F 42 69 72 63 68 00 80 A7 55

转换为 ascii 如下:

Foliage_Evergreen�ÿÿÿ�
Foliage_Birch�€§U

我如何将这些字节分成一个列表并将它们转换为字节值的文本列表?我无法理解我将如何去做......这就是我现在正在做的事情:

OpenFileDialog openFileDialog1 = new OpenFileDialog();

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
string line = System.IO.File.ReadAllText(openFileDialog1.FileName);
byte[] bytes = Encoding.ASCII.GetBytes(line);
List<string> listtext = line.Split('.').ToList();
listBox1.DataSource = listtext;

标签: c#

解决方案


您不应该这样做,因为某些文件会因编码异常而崩溃:

string line = System.IO.File.ReadAllText(openFileDialog1.FileName);
byte[] bytes = Encoding.ASCII.GetBytes(line);

改为使用File.ReadAllBytes,无需读取文本然后转换为字节。

然后你需要将字节数组解析到你的记录中。

根据您的示例数据,您的格式使用 0 作为字段分隔符,并且字符串前面加上它们的长度。这是一个未经测试的解析示例:

static IEnumerable<(string, Color)> parse( byte[] data )
{
    for( int p = 0; p < data.Length; )
    {
        // '\0'
        if( 0 != data[ p++ ] ) throw new ApplicationException();
        // String length byte
        int length = data[ p++ ];
        // The string; assuming the encoding is UTF8
        string name = Encoding.UTF8.GetString( data, p, length );
        p += length;
        // '\0'
        if( 0 != data[ p++ ] ) throw new ApplicationException();
        // 3 color bytes, assuming the order is RGB
        Color color = Color.FromArgb( 0xFF, data[ p ], data[ p + 1 ], data[ p + 2 ] );
        p += 3;
        yield return (name, color);
    }
}

推荐阅读