c# - 我如何将文件(将 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;
解决方案
您不应该这样做,因为某些文件会因编码异常而崩溃:
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);
}
}
推荐阅读
- python - 步进电机控制的 time.sleep 替代方案
- ios - 如何一一显示警报窗口 SWIFT
- c++ - 在 MPI 中跨多个进程创建本地结构时出现分段错误
- javascript - Javascript 对象传播的对象可能具有未定义的对象作为其属性中的数据
- reactjs - 将符号添加到自定义图例布局 - Highcharts React
- sql - SQL 使用条件填充前导行
- django - 在 Django 中使用 SelectMultiple 保存失败
- c++ - rapidjson::Value 的 c++ 模板
- python - 根据最后一个字母对单词进行分组
- asp.net-core - RazorEngine.NetCore:当前上下文中不存在名称“PopWriter”