【问题标题】:Embedding a file into C# .NET application and then reading it in slowly?将文件嵌入到 C# .NET 应用程序中,然后慢慢读取?
【发布时间】:2010-01-06 08:43:57
【问题描述】:

我有一个相当大的资源 (2MB) 正在嵌入到我的 C# 应用程序中...我想知道将其读入内存,然后将其写入磁盘以供以后处理?

我已将资源作为构建设置嵌入到我的项目中

任何示例代码都将帮助我启动。

【问题讨论】:

  • “作为构建设置”没有任何意义。您是在“资源”选项卡中看到它还是在“解决方案”窗口中看到它?

标签: .net visual-studio resources clr


【解决方案1】:

您需要从磁盘流式传输资源,因为 .NET Framework 可能在您访问它们之前不会加载您的资源(我不是 100% 确定,但我相当有信心)

当您流式传输内容时,您还需要将它们写回磁盘。

请记住,这会将文件名创建为“YourConsoleBuildName.ResourceName.Extenstion”

例如,如果您的项目目标名为“ConsoleApplication1”,而您的资源名称为“My2MBLarge.Dll”,那么您的文件将创建为“ConsoleApplication1.My2MBLarge.Dll” -- 当然,您可以修改它如您所见,填充合适。

    private static void WriteResources()
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        String[] resources = assembly.GetManifestResourceNames();
        foreach (String name in resources)
        {
            if (!File.Exists(name))
            {
                using (Stream input = assembly.GetManifestResourceStream(name))
                {
                    using (FileStream output = new FileStream(Path.Combine(Path.GetTempPath(), name), FileMode.Create))
                    {
                        const int size = 4096;
                        byte[] bytes = new byte[size];

                        int numBytes;
                        while ((numBytes = input.Read(bytes, 0, size)) > 0)
                            output.Write(bytes, 0, numBytes);
                    }
                }
            }
        }
    }

【讨论】:

    【解决方案2】:
    var assembly = Assembly.GetExecutingAssembly();
    using (var stream = assembly.GetManifestResourceStream("namespace.resource.txt"))
    {
        byte[] buffer = new byte[stream.Length];    
        stream.Read(buffer, 0, buffer.Length);
        File.WriteAllBytes("resource.txt", buffer);
    }
    

    【讨论】:

      【解决方案3】:

      尝试以下方法:

      Assembly Asm = Assembly.GetExecutingAssembly();
      var stream = Asm.GetManifestResourceStream(Asm.GetName().Name + ".Resources.YourResourceFile.txt");
      var sr = new StreamReader(stream);
      File.WriteAllText(@"c:\temp\thefile.txt", sr.ReadToEnd);
      

      代码假定您的嵌入文件名为YourResourceFile.txt,并且它位于项目中名为Resources 的文件夹中。当然,c:\temp\ 文件夹必须存在并且是可写的。

      希望对你有帮助。

      /克劳斯

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 2011-04-24
        • 1970-01-01
        • 1970-01-01
        • 2012-12-06
        • 2022-01-24
        • 2017-01-13
        • 2019-06-12
        • 1970-01-01
        相关资源
        最近更新 更多