代码之家  ›  专栏  ›  技术社区  ›  halivingston

将文件嵌入C.NET应用程序,然后慢慢地读取?

  •  0
  • halivingston  · 技术社区  · 16 年前

    我有一个相当大的资源(2MB),我将它嵌入到我的C应用程序中…我想知道把它读到内存中,然后把它写到磁盘上,以便以后处理吗?

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

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

    3 回复  |  直到 16 年前
        1
  •  3
  •   mjsabby    16 年前

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

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

    记住,这将创建文件名为“yourconsolebuildname.resourcename.extension”

    例如,如果您的项目目标名为“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
  •  2
  •   Darin Dimitrov    16 年前
    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
  •  2
  •   Klaus Byskov Pedersen    16 年前

    尝试以下操作:

    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\ 必须存在且可写。

    希望它有帮助。

    克劳斯