//文件目录
string path = @"C:\Users\Administrator\Documents\Test\a.txt";
string path2 = @"F:\b.txt";
//如果文件2不存在,创建文件2
if (!File.Exists(path2))
{
FileStream stream = File.Create(path2);
//完毕要后关闭流,否则后面会出错,因为流被这一步占用,后面无法使用
stream.Close();
}
//如果文件存在,就读取,否则跑出异常
if (File.Exists(path))
{
//建立读取和写入流
FileStream reader = File.OpenRead(path);
FileStream writer = File.OpenWrite(path2);
//每次读取的最大字节
int maxByte = 100;
while(true)
{
//存储每次读取的字节数组
byte[] bytes = new byte[maxByte];
//返回每次读取到的字节数,前面的都是最大字节数,当最后一次时,剩余多少
//个字节,就会读取多少个字节,当到达文件末尾时,返回0
int byteCount = reader.Read(bytes, 0, maxByte);
//写入字节,注意不是写入最大读取字节数,而是每次读取到的字节数
writer.Write(bytes, 0, byteCount);
//如果读取到文件末尾,结束
if (byteCount == 0)
{
break;
}
}
//关闭读写流
reader.Close();
writer.Close();
}
else
{
throw new Exception("文件不存在");
}
读写文件Filestream
最新推荐文章于 2020-10-14 16:42:30 发布