需要引入的命名空间 : System.IO
C#已经封装好的文件拷贝API:
System.IO.File.Copy(); //文件拷贝
System.IO.File.ReadAllBytes(); //读取文件的所有字节组
System.IO.File.WriteAllBytes(); //将字节组写入文件
下面将自己动手,使用文件流的读取和写入的方式来实现文件的拷贝,主要分为三步:
public string filePath = @"C:\Users\Njiyue\Desktop\ddd.jpg";
public string copyToPath = @"C:\Users\Njiyue\Desktop\新建文件夹\ccc.jpg";
private void Test()
{
#region 第一步: 获取 两个文件的 “流”
FileInfo oneFileInfo = new FileInfo(filePath);
if (!File.Exists(copyToPath))
File.Create(copyToPath);
FileInfo twoFileInfo = new FileInfo(copyToPath);
FileStream fs1 = oneFileInfo.OpenRead();
FileStream fs2 = twoFileInfo.OpenWrite();
#endregion
#region 第二步: 循环读取写入
byte[] buff = new byte[2048];
int contentLen = fs1.Read(buff, 0, 2048);
while (contentLen != 0)
{
fs2.Write(buff, 0, contentLen);
contentLen = fs1.Read(buff, 0, 2048);
}
#endregion
#region 第三步:关闭读写进程
fs1.Close();
fs2.Close();
fs1 = fs2 = null;
#endregion
}