C# 使用FileStream进行文件复制操作
使用文件流进行操作,如下,其中注释部分是和非注释部分一样的,但是使用using语句是执行完后自动释放内存,而注释部分是手动释放。
CopyFile方法中,缓冲区大小设为1024*1024字节,也就是1MB,Read方法和Write方法中,第一个参数都是缓冲区数组,第二个参数都是偏移量,这个量是在缓冲区中的偏移量,不要搞错,一般为0;第三个参数是要从缓冲区读取或写入的字节数。不同的是Read方法有返回值,为int类型,表示读取的有效字节数。两个方法在成功读取或写入后,再次读取或写入时,位置会移动到成功读取或写入字节后的位置,按我的理解应该是这个意思:第一次读了1M字节,再读的时候就从1M零一字节开始,依次类推。
class Program
{
static void Main(string[] args)
{
string sourcePath = @"K:视频前前前世 (movie ver.) RADWIMPS MV.mp4";
string targetPath = @"C:UserscyhuDesktopcopy.mp4";
Console.WriteLine("start!");
CopyFile(sourcePath, targetPath);
Console.WriteLine("complete!");
Console.ReadKey();
}
public static void CopyFile(string sourcePath, string targetPath)
{
//FileStream fs = new FileStream(sourcePath, FileMode.OpenOrCreate, FileAccess.Read);
//FileStream fsNew = new FileStream(targetPath, FileMode.OpenOrCreate, FileAccess.Write);
//byte[] buffer = new byte[1024 * 1024];
//while (true)
//{
// int len = fs.Read(buffer, 0, buffer.Length);
// if (len == 0)
// {
// break;
// }
// fsNew.Write(buffer, 0, len);
//}
//fsNew.Close();
//fs.Close();
using (FileStream fs = new FileStream(sourcePath,FileMode.OpenOrCreate,FileAccess.Read))
{
using (FileStream fsNew = new FileStream(targetPath,FileMode.OpenOrCreate,FileAccess.Write))
{
byte[] buffer = new byte[1024 * 1024];
while (true)
{
int len = fs.Read(buffer, 0, buffer.Length);
if (len == 0)
{
break;
}
fsNew.Write(buffer, 0, len);
}
}
}
}
}
鲁公网安备 37148202000241号