文件流
//2、使用FileStream写入数据 使用大内存数据 using()自动释放文件流
using (FileStream fileWrite = new FileStream(@"C:\Users\Administrator\Desktop\csharpTest\1.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
string str = "我是filestream写入内容定义字节数组 设置每次读取文件流的大小把实际读取到的字节转为字符串";
byte[] buffer = Encoding.UTF8.GetBytes(str);
fileWrite.Write(buffer, 0, buffer.Length);
}
Console.WriteLine("写入数据成功!");
Console.ReadKey();
多媒体文件复制FileStream
static void Main(string[] args)
{
string srouce = @"C:\Users\Administrator\Desktop\csharpTest\使用FileStream实现多媒体文件的复制.avi";
string target = @"C:\Users\Administrator\Desktop\csharpTest\new多媒体文件.avi";
CopyMedia(srouce, target);
Console.WriteLine("复制成功,请查看!");
Console.ReadKey();
}
/// <summary>
/// 复制多媒体应用
/// </summary>
/// <param name="source">文件的来源</param>
/// <param name="target">目标文件</param>
public static void CopyMedia(string source, string target)
{
Stopwatch sw = new Stopwatch();
//创建一个读取流
using (FileStream fileRead = new FileStream(source, FileMode.Open, FileAccess.Read))
{
//创建一个写入流
using (FileStream fileWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
{
sw.Start();
byte[] buffer = new byte[1024 * 1024 * 5]; //字节数组buffer,每次下载的大小5兆
//因为文件过大,需要循环读取
while (true)
{
int r = fileRead.Read(buffer, 0, buffer.Length); //fileRead大小为34.9mb 每次buffer为5mb 循环了七次
//r=5,5,5,5,5,5,4.9,0 第七次读取时为0mb
if (r == 0) //说明多媒体文件流读完了
{
//break;
return;
sw.Stop();
}
fileWrite.Write(buffer, 0, r); //写入fileWrite 每次buffer为5mb 写完为止
}
}
}
}