当前位置:首页 > 代码相关 > 正文内容

C# 使用FileStream进行文件复制操作

admin5年前 (2020-05-11)代码相关9132

使用文件流进行操作,如下,其中注释部分是和非注释部分一样的,但是使用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);
                    }
                }
            }
        }
    }


扫描二维码推送至手机访问。

版权声明:本文由lovedm.club发布,如需转载请注明出处。

本文链接:https://www.lovedm.club/?id=47

分享给朋友:

“C# 使用FileStream进行文件复制操作” 的相关文章

C# 委托

C# 委托

Action和Func是.NET类库的内置委托,以简便使用。Func有17个重载还可以使用delegate关键字创建委托下面的代码展示了这三种使用委托的方法namespace _20200327 {     public delegat...

C# 控制某句代码只执行一次

这两天用C#写了个2048游戏练手,在需求上如果最终达到了2048,那么应该给出一句提示或者弹出一个消息框,提示达到了2048,而且这个提示只需要展示一次,关闭提示后应该继续游戏而不会重复提示,可以使用bool类型的全局变量进行控制。如下:public partial class...

C# 正则表达式(2)

// pattan = @"[^ahou]"; 表示匹配除ahou之外的字符,^在表示反义 string res4 = Regex.Replace(s, @"[^ahou]",&...

C#(或者Java)反转数组

将原数组反转,如[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]反转后变为[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]因为数组是引用类型,所以直接在方法中处理即可,C#和Java写法一样,如下:      &nb...

C# Stack堆栈

Stack代表了一个先入后出的对象集合。有以下常用方法:表 3Clear()从 Stack 中移除所有对象。Contains(Object)确定某元素是否在 Stack 中。CopyTo(Array, Int32)从指定的数组索引处开始,将 Stac...