从C#应用程序中提取嵌入资源时遇到问题

时间:2013-07-19 04:28:53

标签: c# embedded-resource

这里的想法是将批处理文件从嵌入式资源提取到C驱动器上的临时目录,然后运行该提取的批处理文件。我遇到的问题是“对象引用未设置为对象实例”的错误。

代码是:

public static void ExtractResource()
    {
        using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(Namespace.Properties.Resources.Backup))
        {
            byte[] buffer = new byte[s.Length];
            s.Read(buffer, 0, buffer.Length);
            using (var sw = new BinaryWriter(File.Open(@"C:\test.bat", FileMode.OpenOrCreate)))
            {
                sw.Write(buffer);
            }
        }
    }

此行发生错误:

byte[] buffer = new byte[s.Length];

3 个答案:

答案 0 :(得分:1)

如果您嵌入了资源,那么它将生成静态方法以获取嵌入文件内容的内容,在内部调用ResourceManager.GetString方法,请尝试以下

using (var sw = new BinaryWriter(File.Open(@"C:\test.bat", FileMode.OpenOrCreate)))
{
   writer.Write(Namespace.Properties.Resources.Backup);
}

答案 1 :(得分:0)

以下内容如何为您服务?

    public static  class Program
        {
            public static void Main()
            {
                ExtractResource();
            }

            public static void ExtractResource()
            {
                //replace your embedded file by yours 
                using (var inputStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.XMLFile1.xml"))
                {
                    using(var outputStream = File.Create(@"D:\test.bat"))
                    {
                        /// fix your buffer size 8192,4096 etc.
                        var buffer = new byte[8192];

                        int numberOfBytesRead;
                        while (inputStream != null && (numberOfBytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            outputStream.Write(buffer, 0, numberOfBytesread);
                        }
                    }
                }

            }
       }

答案 2 :(得分:0)

听起来好像没有返回流,或者它没有报告长度。

另外,不要一次读取整个流,它的内存效率不高,并且当您开始使用网络流或大型文件时,它们不是最好的模式,而实际上可能无法报告它们的实际长度。

public void WriteResrouce(string resourcePath, string targetPath)
{
    var buffer = new byte[64 * 1024]; //i've picked 64k as a reasonable sized block
    using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath))
    using (var sw = new BinaryWriter(File.Open(targetPath, FileMode.OpenOrCreate)))
    {
        var readCount = -1;
        while (0 < (readCount = s.Read(buffer, 0, buffer.Length)))
        {
            sw.Write(buffer, 0, readCount);
        }
    }
}