如何读取,然后写入C#中的嵌入式资源

每当我尝试执行以下代码时,我都会收到错误“Stream is not writable”。 我知道在内存中仍然有对流的引用,但我不知道如何解决这个问题。 这两个代码块按顺序调用。 我认为第二个可能是函数调用或者调用堆栈中的两个更深层,但我认为这不重要,因为我在第一个块中有“using”语句应该自动清理流。 我确信这是C#中的常见任务,我只是不知道如何做到这一点……

string s = ""; using (Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Datafile.txt")) { using (StreamReader sr = new StreamReader(manifestResourceStream)) { s = sr.ReadToEnd(); } } 

 string s2 = "some text"; using (Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Datafile.txt")) { using (StreamWriter sw = new StreamWriter(manifestResourceStream)) { sw.Write(s2); } } 

任何帮助将非常感谢。 谢谢!

安德鲁

嵌入式资源被编译到您的程序集中,您无法编辑它们。

如上所述,嵌入资源是只读的。 我的建议,如果适用,( 例如,您的嵌入式资源是数据库文件,XML,CSV等 )将提取空白资源到与程序相同的位置,并读取/写入提取的资源。

示例伪代码:

 if(!Exists(new PhysicalResource())) //Check to see if a physical resource exists. { PhysicalResource.Create(); //Extract embedded resource to disk. } PhysicalResource pr = new PhysicalResource(); //Create physical resource instance. pr.Read(); //Read from physical resource. pr.Write(); //Write to physical resource. 

希望这可以帮助。

额外:

您的嵌入式资源可能完全空白,包含数据结构和/或默认值。

有点晚了,但对于后代=)关于嵌入式.txt:

是的,在运行时你无法编辑嵌入式,因为它是嵌入的。 您可以使用反汇编程序,但只能使用outter程序集,您将在当前上下文中加载。

如果您想在程序启动之前向资源写入一些实际信息,并且不将数据保存在单独的文件中,则会出现黑客攻击。

我曾经在winCE和compact .Net上工作过一段时间,你不能允许在运行时使用ResourceManager存储字符串。 我需要一些动态信息,以便在它实际抛出启动之前捕获dllNotFoundException。 所以我制作了嵌入式txt文件,我在预构建事件中填写了该文件。

像这样:

 cd $(ProjectDir) dir ..\bin\Debug /ad /b> assemblylist.txt 

这里我在调试文件夹中获取文件

和阅读:

 using (var f = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Market_invent.assemblylist.txt"))) { str = f.ReadToEnd(); } 

因此,您可以在预构建事件中继续执行所有操作。

请享用! 它非常有用,可以存储一些重要信息并帮助避免冗余操作。