FileStream复制文件注意事项

使用FileStream读取文件时,为避免将大文件一次性全部读取到内存中,我们经常会声明一个byte[]做为临时存储空间,然后循环读取内容:

using (FileStream fs = File.OpenRead(path))
{
    byte[] b = new byte[1024];
    UTF8Encoding temp = new UTF8Encoding(true);
    while (fs.Read(b, 0, b.Length) > 0)
    {
        Console.WriteLine(temp.GetString(b));
    }
}

同理,在复制文件时我们也不希望将大文件一次性都读取到内存中,同样可以声明一个byte[]做为临时存储空间:

public void CopyFile(string sourcepath, string destpath)
{
    using (FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read))
    {
        using (FileStream fs2 = new FileStream(destpath, FileMode.Create, FileAccess.Write))
        {
            byte[] b = new byte[1024];
            while (fs.Read(b, 0, b.Length) > 0)
            {
                fs2.Write(b, 0, b.Length);
            }
        }
    }
}

问题来了,当最后一次读取不满1024字节时,byte数组的剩余项都为0,这样在写入时将致使新文件比原文件占用更多的空间:



只需将代码稍加修改即可:

public void CopyFile(string sourcepath, string destpath)
{
    using (FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read))
    {
        using (FileStream fs2 = new FileStream(destpath, FileMode.Create, FileAccess.Write))
        {
            byte[] b = new byte[1024];
            int l = 0;
            while ((l = fs.Read(b, 0, b.Length)) > 0)
            {
                fs2.Write(b, 0, l);
            }
        }
    }
}


上一篇: C# short转byte
下一篇: png格式图片详解
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
最新日志:
评论: 0 | 引用: 0 | 查看次数: 4763
发表评论
登录后再发表评论!