首页 > 其他分享 >使用FileStream来实现复制功能

使用FileStream来实现复制功能

时间:2022-09-21 17:37:42浏览次数:64  
标签:功能 string FileStream source 复制 buffer new target

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);

                }
            }
        }

 

标签:功能,string,FileStream,source,复制,buffer,new,target
From: https://www.cnblogs.com/zerryLuo/p/16716419.html

相关文章