刚好前天写了一个类,送你了.
public enum ArchiveMode
{
store,
load,
}
public static string BytesToString(byte[] bs, int start, int bsLen)
{
string ss = Encoding.Unicode.GetString(bs, start, bsLen);
return ss;
}
public static void StringToBytes(string text, byte[] bs, out int bsLen)
{
bsLen = Encoding.Unicode.GetBytes(text, 0, text.Length, bs, 0);
}
public class Archive
{
FileStream m_fs = null;
ArchiveMode m_Mode;
public Archive(FileStream fs, ArchiveMode mode)
{
m_Mode = mode;
m_fs = fs;
}
public void Close()
{
m_fs = null;
}
public bool IsStore
{
get { return m_Mode == ArchiveMode.store; }
}
public bool IsLoad
{
get { return m_Mode == ArchiveMode.load; }
}
public DateTime ReadDataTime()
{
if (IsStore)
throw new Exception("store模式下不允许读取");
byte[] bs8 = new byte[8];
m_fs.Read(bs8, 0, 8);
long l = System.BitConverter.ToInt64(bs8, 0);
DateTime dt = new DateTime(l);
return dt;
}
public void WriteDataTime(DateTime dt)
{
if (IsLoad)
throw new Exception("load模式下不允许写入");
byte[] bs = System.BitConverter.GetBytes(dt.ToBinary());
m_fs.Write(bs, 0, 8);
}
public int ReadCount()
{
if (IsStore)
throw new Exception("store模式下不允许读取");
byte[] bs = new byte[4];
m_fs.Read(bs, 0, 4);
return System.BitConverter.ToInt32(bs, 0);
}
public void WriteCount(int n)
{
if (IsLoad)
throw new Exception("load模式下不允许写入");
byte[] bs = System.BitConverter.GetBytes(n);
//if (n > 0xFFFF)
//{
// m_fs.Write(System.BitConverter.GetBytes(0xFFFF), 0, 2);
//}
m_fs.Write(bs, 0, bs.Length);
}
public long ReadLong()
{
if (IsStore)
throw new Exception("store模式下不允许读取");
byte[] bs = new byte[8];
m_fs.Read(bs, 0, 8);
return System.BitConverter.ToInt64(bs, 0);
}
public void WriteLong(long n)
{
if (IsLoad)
throw new Exception("load模式下不允许写入");
byte[] bs = System.BitConverter.GetBytes(n);
m_fs.Write(bs, 0, bs.Length);
}
public int Read(byte[] bs, int count)
{
if (IsStore)
throw new Exception("store模式下不允许读取");
return m_fs.Read(bs, 0, count);
}
public void Write(byte[] bs, int count)
{
if (IsLoad)
throw new Exception("load模式下不允许写入");
m_fs.Write(bs, 0, count);
}
public void WriteString(string text)
{
int len = text.Length * 2;
byte[] bs = new byte[len + 8];
int oulen = 0;
F.StringToBytes(text, bs, out oulen);
WriteCount(oulen);
Write(bs, oulen);
}
public string ReadString()
{
int len = ReadCount();
byte[] bs = new byte[len];
Read(bs, len);
return F.BytesToString(bs, 0, len);
}
}
温馨提示:答案为网友推荐,仅供参考