今天我们来看看C#
中如何生成anb文件。
这个anb文件本来是要对接别的平台的,人家提供给我们一个协议,然后通过程序来生成,然后对方会根据生成的anb文件进行解析,然后得到心电图啥的。
代码如下:
private void createFileBtn_Click(object sender, EventArgs e)
{
string fileName = “demo.anb”;
string filePath = @“D:” + fileName;
bool isFile = Directory.Exists(filePath);
if (isFile)
//{
// Directory.CreateDirectory(filePath);
//}
//else
{
Directory.Delete(filePath);
// Directory.CreateDirectory(filePath);
}
string txtJson = this.txtJson.Text;
if (string.IsNullOrWhiteSpace(txtJson))
{
MessageBox.Show(“请输入对应的字符串”);
return;
}
string fileOtherPath = this.txtFilePath.Text;
if (string.IsNullOrWhiteSpace(fileOtherPath))
{
MessageBox.Show(“请输入ECG文件路径”);
return;
}
// byte[] txtByte = Encoding.Unicode.GetBytes(txtJson);
FileStream fs = new FileStream(fileOtherPath, FileMode.Open, FileAccess.Read);
byte[] fsEcg = new byte[fs.Length];
fs.Read(fsEcg, 0, Convert.ToInt32(fs.Length));
fs.Close();
var allVoltageText = File.ReadAllText(fileOtherPath);allVoltageText = allVoltageText.Trim('"');var allVoltageValues = allVoltageText.Split(',').Select(t => short.Parse(t)).ToArray();//List<byte> list = new List<byte>();//list.AddRange(txtByte);//list.AddRange(fsEcg);//byte[] data = list.ToArray();//Stream input = new MemoryStream(data);//FileStream file = new FileStream(filePath, FileMode.OpenOrCreate);//BinaryWriter binaryWriter = new BinaryWriter(file);//for (int i = 0; i < txtByte.Length; i++)//{// binaryWriter.Write(txtByte[i]);//}//for (int i = 0; i < fsEcg.Length; i++)//{// binaryWriter.Write(fsEcg[i]);//}//char[] cChar = Encoding.ASCII.GetChars(txtByte);//binaryWriter.Write(cChar);//char[] ecgChar = Encoding.ASCII.GetChars(fsEcg);//binaryWriter.Write(ecgChar);//binaryWriter.Flush();//binaryWriter.Close();//file.Close();Stream stream = new FileStream(filePath, FileMode.OpenOrCreate);//int count = fsEcg.Length >> 1;//short[] dest = new short[count];//for (int i = 0; i < count; i++)//{// dest[i] = (short)(fsEcg[i * 2] << 8 | fsEcg[2 * i + 1] & 0xff);//}Write(stream, txtJson, allVoltageValues);stream.Dispose();}
/// <summary>/// 生成.anb文件/// </summary>/// <param name="stream">目标文件流</param>/// <param name="header">文件头结构</param>/// <param name="leadDatas">心电数据</param>/// <param name="convertData"></param>/// <returns></returns>public static bool Write(Stream stream, string header, short[] leadDatas){BinaryWriter bw = new BinaryWriter(stream);try{byte[] headerBuffer = Encoding.UTF8.GetBytes(header);bw.Write(headerBuffer.Length);bw.Write(headerBuffer);for (int i = 0; i < leadDatas.Length; i++){bw.Write(leadDatas[i]);}//if (header.IsTimeOrder)//{// for (int i = 0; i < leadDatas[0].Length; i++)// {// for (int j = 0; j < leadDatas.Length; j++)// {// bw.Write(convertData(leadDatas[j][i]));// }// }//}//else//{// foreach (short[] leadData in leadDatas)// {// foreach (short data in leadData)// {// bw.Write(convertData(data));// }// }//}}catch (Exception ex){Console.WriteLine(ex);return false;}finally{bw.Flush();}return true;}}}
生成的如下图所示: