将文件嵌入C#.NET应用程序,然后缓慢地读取?
我有一个相当大的资源(2MB)正在嵌入到我的C#应用程序中。。。我想知道将它读入内存,然后将其写入磁盘以供以后处理 我已将资源作为构建设置嵌入到我的项目中将文件嵌入C#.NET应用程序,然后缓慢地读取?,.net,visual-studio,resources,clr,.net,Visual Studio,Resources,Clr,我有一个相当大的资源(2MB)正在嵌入到我的C#应用程序中。。。我想知道将它读入内存,然后将其写入磁盘以供以后处理 我已将资源作为构建设置嵌入到我的项目中 任何示例代码都可以帮助我启动。您需要从磁盘中导入资源,因为在您访问资源之前,.NET Framework可能不会加载您的资源(我不是100%确定,但我相当有信心) var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestRe
任何示例代码都可以帮助我启动。您需要从磁盘中导入资源,因为在您访问资源之前,.NET Framework可能不会加载您的资源(我不是100%确定,但我相当有信心)
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);
}
在流式传输内容时,还需要将其写回磁盘
记住,这将创建文件名为“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);
}
}
}
}
}
请尝试以下操作:
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“作为构建设置”没有任何意义。您是在“资源”选项卡中看到它,还是在“解决方案”窗口中看到它?