class Program {
#region IO流,文件拷贝演示:
/*
* 文件流拷贝大文件:
* 步骤:
* 读取(源路径)
* 写入(目标路径)
*/
string sourcePath = @"S:\Work\Coding.txt";
string targetPath = @"H:\Coding.txt";
using (Stream fsRead = File.OpenRead(sourcePath)) // 读取流
{
using (Stream fsWrite = File.OpenWrite(targetPath)) // 写入流
{
// 字节缓冲数组,4M
byte[] buffer = new byte[4 << 20];
int count = 0; // 当前读取到的字节数
float progress = 0; // 当前写入的进度
// 写入过程 fsRead.CopyTo(fsWiter);
while ((count = (fsRead.Read(buffer, 0, buffer.Length))) > 0)
{
fsWrite.Write(buffer, 0, count);
fsWrite.Flush(); // 刷新缓冲区,写入到设备
progress = (float)fsWrite.Position / fsRead.Length;
Console.WriteLine("文件以拷贝 " + progress * 100 + "%");
}
}
}
/**IO流中必须了解的2个抽象基类
* 字节流(Stream)
* 字符流(TextReader、TextWriter)
* ... 其他的请看msdn库
* */
////TextReader tRead = new StreamReader(sourcePath);
////Console.WriteLine(tRead.ReadToEnd()+"123456468798798");
////File类操作文件的一些静态方法,通过 Reflector 工具可看出封装有流的操作
//File.ReadAllText("path");
//File.WriteAllText("path", "contents");
//File.AppendAllText("path", "contents");
#endregion
}
C#IO流总结
最新推荐文章于 2025-05-23 19:37:51 发布