写的程序集资源流磁盘文件 [英] Write file from assembly resource stream to disk

查看:137
本文介绍了写的程序集资源流磁盘文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法找到一个更有效的方式来复制嵌入的资源到磁盘,比以下内容:

I can't seem to find a more efficient way to "copy" an embedded resource to disk, than the following:

using (BinaryReader reader = new BinaryReader(
    assembly.GetManifestResourceStream(@"Namespace.Resources.File.ext")))
{
    using (BinaryWriter writer
        = new BinaryWriter(new FileStream(path, FileMode.Create)))
    {
        long bytesLeft = reader.BaseStream.Length;
        while (bytesLeft > 0)
        {
            // 65535L is < Int32.MaxValue, so no need to test for overflow
            byte[] chunk = reader.ReadBytes((int)Math.Min(bytesLeft, 65536L));
            writer.Write(chunk);

            bytesLeft -= chunk.Length;
        }
    }
}

目前似乎没有更直接的方式进行复制,除非我失去了一些东西......

There appears to be no more direct way to do the copy, unless I'm missing something...

推荐答案

我不知道为什么你使用 BinaryReader在 / 的BinaryWriter 可言。个人而言,我会用一个有用的工具方法开始:

I'm not sure why you're using BinaryReader/BinaryWriter at all. Personally I'd start off with a useful utility method:

public static void CopyStream(Stream input, Stream output)
{
    // Insert null checking here for production
    byte[] buffer = new byte[8192];

    int bytesRead;
    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}

然后调用它:

then call it:

using (Stream input = assembly.GetManifestResourceStream(resourceName))
using (Stream output = File.Create(path))
{
    CopyStream(input, output);
}

您可以改变路线的缓冲区的大小,或者将其作为参数传递给方法 - 但主要的一点是,这是的简单的code。是不是更有效?都能跟得上。你确定你真的的需要的这个code更有效率?你真的有百兆你需要写到磁盘?

You can change the buffer size of course, or have it as a parameter to the method - but the main point is that this is simpler code. Is it more efficient? Nope. Are you sure you really need this code to be more efficient? Do you actually have hundreds of megabytes you need to write out to disk?

我发现我很少需要code是超高效,但我几乎总是需要它是简单的。在性能差的那种,你可能这和巧方法之间看到(如果有的话甚至可用)不可能是一个复杂变化的影响(如:O(N)为O(log n)的) - 和这是的性能增益它真的可以值得追逐的类型。

I find I rarely need code to be ultra-efficient, but I almost always need it to be simple. The sort of difference in performance that you might see between this and a "clever" approach (if one is even available) isn't likely to be a complexity-changing effect (e.g. O(n) to O(log n)) - and that's the type of performance gain which really can be worth chasing.

编辑:正如评论指出的那样,.NET 4.0有<一个href="http://msdn.microsoft.com/en-us/library/system.io.stream.copyto.aspx"><$c$c>Stream.CopyTo所以你不必code这件事吧。

As noted in comments, .NET 4.0 has Stream.CopyTo so you don't need to code this up yourself.

这篇关于写的程序集资源流磁盘文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆