使用FileStream来实现复制功能

static void Main(string[] args)
        {
            string source = @"D:\桌面\demo.txt";
            string target = @"D:\桌面\demo2.txt";
            CopyFile(source, target);

        }
        public static void CopyFile(string source, string target)
        {
            using (FileStream fsRead = new FileStream(source, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    while (true)
                    {
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        if (r == 0)
                        {
                            break;
                        }
                        fsWrite.Write(buffer, 0, r);
                    }

                }
            }
        }

 或者更加简便的操作

static void Main(string[] args)
        {
            string source = @"D:\桌面\demo.txt";
            string target = @"D:\桌面\demo2.txt";
            CopyFile(source, target);

        }
        public static void CopyFile(string source, string target)
        {
            using (FileStream fsRead = new FileStream(source, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    //byte[] buffer = new byte[1024 * 1024 * 5];
                    //while (true)
                    //{
                    //    int r = fsRead.Read(buffer, 0, buffer.Length);
                    //    if (r == 0)
                    //    {
                    //        break;
                    //    }
                    //    fsWrite.Write(buffer, 0, r);
                    //}
                    fsRead.CopyTo(fsWrite);

                }
            }
        }

 

posted @ 2022-09-21 17:25  ZerryLuo  阅读(30)  评论(0编辑  收藏  举报