关于C#.dat文件读取

ige5460 2008-12-17 11:47:21
.dat文件是c创建的,格式是4个字节的int和60个字节的char(中文,不足为/0)连续保存,

现在在c#中要如何读取
...全文
794 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
yinjianbbq20 2009-09-10
  • 打赏
  • 举报
回复
过来看看精华帖的 学习学习
GTX280 2008-12-17
  • 打赏
  • 举报
回复
用FileStream

FileStream fs = new FileStream(@"C:\test.dat", FileMode.Open, FileAccess.Read);
int numBytesToRead = (int)fs.Length;
int numBytesReaded = 0;
while (numBytesToRead > 0)
{
byte[] intBytes = new byte[4];
int n = fs.Read(intBytes, numBytesReaded, 4);
numBytesReaded += n;
numBytesToRead -= n;
if (n == 0)
{
break;
}
int value = BitConverter.ToInt32(intBytes, 0);//get the int value
byte[] charBytes = new byte[60];
n = fs.Read(intBytes, numBytesReaded, 60);
if (n == 0)
{
break;
}
string valueStr = BitConverter.ToString(charBytes, 0);//get the string value
numBytesReaded += n;
numBytesToRead -= n;
}
gomoku 2008-12-17
  • 打赏
  • 举报
回复
You might try this one:


byte[] rawBytes = System.IO.File.ReadAllBytes(@"my.dat");
int i = BitConverter.ToInt32(rawBytes, 0);
string s = Encoding.Default.GetString(rawBytes, 4, 60); //or ASCII encoding, according to your impelmentation
GTX280 2008-12-17
  • 打赏
  • 举报
回复

FileStream fs = new FileStream(@"C:\test",FileMode.Open,FileAccess.ReadWrite);
int value = 265;
byte[] bytesInt = BitConverter.GetBytes(value);
fs.Write(bytesInt, 0, 4);
char[] valueStr = ("这次是测试").ToCharArray();
byte[] bytes = new byte[60];
byte[] strBytes = Encoding.Unicode.GetBytes(valueStr, 0, valueStr.Length);
for (int i = 0; i < 60; i++)
{
if (i < strBytes.Length)
{
bytes[i] = strBytes[i];
}else
{
bytes[i] = 0;//'\0'
}
}
fs.Write(bytes, 0, 60);

      //保存文件
      fs.Flush();
fs.Close();
ige5460 2008-12-17
  • 打赏
  • 举报
回复
非常感谢两位大哥的热心帮助,我这样处理
String[] words = new String[3];
byte[] rawBytes = System.IO.File.ReadAllBytes(@"D:\chinese.dat");
int numBytesToRead = rawBytes.Length;
int numBytesReaded = 0;
while (numBytesToRead > 0)
{
int i = BitConverter.ToInt32(rawBytes, numBytesReaded);
numBytesReaded += 4;
numBytesToRead -= 4;
string s = Encoding.Default.GetString(rawBytes, numBytesReaded, 60);
numBytesReaded += 60;
numBytesToRead -= 60;
words[0] = i.ToString().PadLeft (3);
words[1] = s;
this.dataGridView1.Rows.Add(words);
}

现在还有个问题,就是对字符串做修改后如何按照原来的格式保存
zgke 2008-12-17
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 gomoku 的回复:]
You might try this one:


C# code
byte[] rawBytes = System.IO.File.ReadAllBytes(@"my.dat");
int i = BitConverter.ToInt32(rawBytes, 0);
string s = Encoding.Default.GetString(rawBytes, 4, 60); //or ASCII encoding, according to your impelmentation
[/Quote]

这个根据你字符保存的时候用什么编码就用什么编码读
ige5460 2008-12-17
  • 打赏
  • 举报
回复
执行到
n = fs.Read(charBytes, numBytesReaded, 60);
出错,错误提示:
偏移量和长度超出数组的界限,或者计数大于从索引到源集合结尾处的元素数量。

111,130

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧