C# 用filestream读取文本的问题?

用FileStream的Read方法读取文本中的字符,然后用数组一个字符一个字符储存进去,再用自己输入的字符串进行查找匹配,差不多是这样!

FileStream fs = new FileStream("账号信息.txt",FileMode.Open);
int count = 1;
byte [] bt= new byte[36];
string str1=tbzhao.Text;
while(count!=0)
{
count=fs.Read(bt,0,bt.Length);
string str=System.Text.Encoding.ASCII.GetString(bt);
lbmma.Text=str;
break;
}

fs.Close();

最好上面的代码修改下!

刚好前天写了一个类,送你了.
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);
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-06-07
很不推荐你用这种方式查询字符串,直接操作byte的话很可能会切割字符,像中文都是超过两个byte的,所以极有可能切割字符而找不到你要的文本

再看你的代码没看到什么比较,是不是逻辑写的有问题

最好使用正则表达式来比较
相似回答