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

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

  •  2
  • Andrew  · 技术社区  · 16 年前

    每当我尝试执行以下代码时,我总是得到错误“流不可写”。我知道内存中仍然有对流的引用,但我不知道如何解决这个问题。这两个代码块按顺序调用。我认为第二个调用可能是一个函数调用或调用堆栈中更深的两个调用,但我认为这并不重要,因为我在第一个块中有“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);
        }
    }
    

    任何帮助都将不胜感激。谢谢!

    安得烈

    3 回复  |  直到 10 年前
        1
  •  10
  •   Joachim VR    16 年前

    嵌入的资源已编译到程序集中,无法对其进行编辑。

        2
  •  1
  •   Matthew Layton    14 年前

    如上所述,嵌入的资源是只读的。我的建议,如果适用的话,( 例如,您的嵌入资源是数据库文件、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.
    

    希望这有帮助。

    附加:

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

        3
  •  1
  •   Roma Borodov    10 年前

    有点晚了,但对于后代而言=) 关于embedded.txt:

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

    如果你想在程序启动前向一个资源写入一些实际的信息,并且不把数据保存在一个单独的文件中,那么就有一个黑客攻击。

    我曾经在Wince和Compact.net上做过一些工作,在那里你不允许在运行时使用ResourceManager存储字符串。我需要一些动态信息,以便在dllnotfoundException实际抛出Start之前捕获它。 所以我制作了嵌入的TXT文件,在预构建事件中填充它。

    这样地:

    cd $(ProjectDir)
    dir ..\bin\Debug /a-d /b> assemblylist.txt
    

    在这里,我在debug文件夹中获取文件

    阅读材料:

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

    所以您可以在预构建事件中继续所有操作,运行一些exes。

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