2012-05-29 27 views
0

我需要在使用phalanger以php编写的纯编译dll中嵌入一些资源。 这些是我在Visual Studio中设置为“Embedded Resource”的txt文件。在Phalanger中使用System.Reflection和资源

我的问题是我不能使用Assembly类来获取使用GetManifestResourceStream的资源。

我想这样的代码: 使用SYSTEM \反射\大会

$asm = Assembly::GetExecutingAssembly(); //this gives me mscorlib instead of my dll 
$str = $asm->GetManifestResourceStream("name"); 

我的问题是:我怎么去嵌入资源phalanger访问? 非常感谢

回答

0

我不确定,为什么Assembly :: GetExecutingAssembly()返回一个不正确的值。反正要解决的$ ASM值,可以使用下面的代码:当你发布

$asm->GetManifestResourceStream("TextFile1.txt"); 

$MyType = CLRTypeOf MyProgram; 
$asm = $MyType->Assembly; 

然后你就可以访问嵌入资源,也可以包括标准的资源文件(的.resx)到您的项目,并使用\ SYSTEM \资源\ ResourceManager的

只要注意,目前可以有Phalanger项目中只有一个的.resx

+0

非常感谢,第一个解决方案效果很好!不幸的是,如果我使用流读取器将文本文件读取为字符串(使用ReadToEnd()),在获取真实文件内容之前,我会获取大量未知字节,还有一些文本显示“System.Resources.ResourceReader ...” ”。我在c#ad中编写了相同的代码,只有文件ccontent符合预期。 – user1423242

0

这个问题是旧的,但负责这个问题的Phalanger代码(Php.Core.Emit.AddResourceFile()方法)的一部分并没有改变,因为这是问。我遇到了同样的问题,并且以(几乎)非破解的方式解决了这个问题。您必须提供替代名称(/res:/path/to/filename,alternative-name)才能使其工作。

$asm = clr_typeof('self')->Assembly; 
$resourceStream = $asm->GetManifestResourceStream("filename"); 
$reader = new \System\Resources\ResourceReader($resourceStream); 

$type = $data = null; 
$reader->GetResourceData("alternative-name", $type, $data); 

// and still there are 4 excess bytes 
// representing the length of the resource 
$data = \substr($data, 4); 
$stream = new IO\MemoryStream($data); 

// after this $stream is usable as you would expect 

直白GetManifestResourceStream()(由的Jakub的建议)不起作用,因为Phalanger不使用System.Reflection.Emit.ModuleBuilder.DefineManifestResource()(就像我认为它应该当无法识别的文件格式提供)。它使用ModuleBuilder.DefineResource(),它返回ResourceWriter,而不是仅适用于.resources文件。当你需要阅读你的资源时,这就是要求使用ResourceReader的要求。

注意:这个答案适用于Phalanger master branch at the time of writing和以前的版本,因为大约2011年指出,由于它看起来像一个bug(尤其是需要同时使用原始的和替代名称)。