2010-01-06 50 views
0

我有一个相当大的资源(2MB),我嵌入到我的C#应用​​程序中...我想知道将它读入内存,然后将它写入磁盘以便将其用于以后处理?将文件嵌入到C#.NET应用程序中,然后慢慢读取它?

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

代码的任何试片会帮我启动。

+0

“as build setting”并不意味着什么。您是在资源标签中看到它,还是在解决方案窗口中可见? – 2010-01-06 08:49:27

回答

3

你需要从磁盘资源到流中,因为.NET框架可能直到你访问它们将不会加载你的资源(我不是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); 
        } 
       } 
      } 
     } 
    } 
+0

工程...谢谢添加异常处理 – halivingston 2010-01-06 08:55:12

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); 
} 
2

尝试以下操作:

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

希望它有帮助。

/Klaus