【发布时间】:2012-06-19 21:53:29
【问题描述】:
我有一个用小端编码的二进制文件,其中包含约 250.000 个 var1 值,然后是另一个相同数量的 var2 值。我应该创建一个方法来读取文件并返回一个 DataSet,其中包含 var1 和 var2 列中的这些值。
我正在使用该库:miscutil 在 SO 中多次提到这里,详情请参见这里:will there be an update on MiscUtil for .Net 4?
非常感谢 Jon Skeet 提供它。 :)
我有以下代码工作,我对如何最小化从文件中读取的 for 循环和填充 DataTable 的更好想法感兴趣。有什么建议吗?
private static DataSet parseBinaryFile(string filePath)
{
var result = new DataSet();
var table = result.Tables.Add("Data");
table.Columns.Add("Index", typeof(int));
table.Columns.Add("rain", typeof(float));
table.Columns.Add("gnum", typeof(float));
const int samplesCount = 259200; // 720 * 360
float[] vRain = new float[samplesCount];
float[] vStations = new float[samplesCount];
try
{
if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
{
throw new ArgumentException(string.Format("Unable to open the file: '{0}'", filePath));
}
// at this point FilePath is valid and exists...
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
// We are using the library found here: http://www.yoda.arachsys.com/csharp/miscutil/
var reader = new MiscUtil.IO.EndianBinaryReader(MiscUtil.Conversion.LittleEndianBitConverter.Little, fs);
int i = 0;
while (reader.BaseStream.Position < reader.BaseStream.Length) //while (pos < length)
{
// Read Data
float buffer = reader.ReadSingle();
if (i < samplesCount)
{
vRain[i] = buffer;
}
else
{
vStations[i-samplesCount] = buffer;
}
++i;
}
Console.WriteLine("number of reads was: {0}", (i/2).ToString("N0"));
}
for (int j = 0; j < samplesCount; ++j)
{
table.Rows.Add(new object[] { j + 1, vRain[j], vStations[j] });
}
}
catch (Exception exc)
{
Debug.WriteLine(exc.Message);
}
return result;
}
【问题讨论】:
-
"此时 FilePath 有效且存在..." 检查 File.Exists 并打开文件为文件不存在提供了机会窗口(竞争条件)。您应该跳过 File.Exists 测试,因为它是多余的。此外,尝试打开它会产生比 ArgumentException 更具描述性的 FileNotFoundException。
-
感谢 Tergiver,会考虑您的意见并完善我的代码。
标签: c# .net binary-data endianness