如何异步读取文件
- 提问者网友:战魂
- 2021-03-10 11:22
- 五星知识达人网友:鸠书
- 2021-03-10 12:42
- 1楼网友:鸠书
- 2021-03-10 13:07
public delegate void mydelegatefile(byte[] bb);
public class readfilestate
{
public filestream fs;
public byte[] bytefile;
public int bytenum;
}
/// <summary>
/// 打开一个文本文件,显示在richtextbox中
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void o_fs_click(object sender, eventargs e)
{
string s = "";
ofd.filter = "文本文件|*.txt|全部文件|*.*";
ofd.defaultext = "txt";
ofd.filename = "";
try
{
if (ofd.showdialog() == dialogresult.ok)
{
s = ofd.filename;
fs = new filestream(s,filemode.open,fileaccess.read);
readfilestate rfs = new readfilestate();
rfs.bytefile = new byte[fs.length];
rfs.fs = fs;
rfs.bytenum = (int)fs.length;
asynccallback ac = new asynccallback(getfileresult);
fs.beginread(rfs.bytefile, 0, (int)fs.length, ac, rfs);
}
}
catch (ioexception iex)
{
messagebox.show(iex.message);
}
}
void getfileresult(iasyncresult iar)
{
try
{
thread.sleep(5000);
readfilestate rfs = (readfilestate)iar.asyncstate;
if (rfs != null)
{
filestream fs = rfs.fs;
int n = fs.endread(iar);
if (rfs.bytefile != null)
{
this.invoke(mdd, rfs.bytefile);
}
else { messagebox.show("当前数组值为空."); }
}
}
catch (ioexception iex)
{
messagebox.show(iex.message);
}
finally
{
fs.close();
}
}
void showfile(byte[] y)
{
//string s = "";
//for (int i = 0; i < y.getlength(0); ++i)
//{
// s = s + y[i].tostring()+" ";
//}
string ss = encoding.getencoding(936).getstring(y);
rtb.text = ss;
//rtb.text ="读取文件字符串的长度是:"+ i.tostring();
}