使用System.IO.Compression.ZipArchive通过反射很难访问可见属性

时间:2019-01-08 23:49:03

标签: c# reflection system.io.compression

库已加载,我能够在调试器中查看ziparchiveentries,但无法通过反射访问ziparchiveentry对象数组的方法或属性:

Assembly CompressionLib = Assembly.LoadWithPartialName("System.IO.Compression");
Module CompressionModule = CompressionLib.GetModule("System.IO.Compression.dll");
Type ZipArchiveType = CompressionModule.GetType("System.IO.Compression.ZipArchive");
Type ZipArchiveEntryType = CompressionModule.GetType("System.IO.Compression.ZipArchiveEntry");
ConstructorInfo UnzipConstructor = ZipArchiveType.GetConstructor(new[] { typeof(System.IO.Stream) });
object UnzipInstance = UnzipConstructor.Invoke(new object[] Plugin.PluginFiles[0].fileData });
MethodInfo UnzipGetEntries = ZipArchiveType.GetMethod("get_Entries");
ICollection UnzippableFilesCollection = (ICollection)UnzipGetEntries.Invoke(UnzipInstance, null);
object[] UnzippableFiles = new ArrayList(UnzippableFilesCollection).ToArray();

这时,我可以在调试器中查看例如:

UnzippableFiles[25]
{pt-br/ACResources.resources.dll}
    Archive: {System.IO.Compression.ZipArchive}
    CompressedLength: 78659
    ExternalAttributes: -2119958528
    FullName: "pt-br/ACResources.resources.dll"
    LastWriteTime: {1/8/2019 7:29:04 AM -08:00}
    Length: 232696
    Name: "ACResources.resources.dll"

但是示例:

ZipArchiveEntryType.GetType().GetProperty("FullName").GetValue(UnzippableFiles[25])

返回错误:

    `'ZipArchiveEntryType.GetType().GetProperty("FullName").GetValue(UnzippableFiles[25])' threw an exception of type 'System.Reflection.TargetException'`
Message: "Object does not match target type."

1 个答案:

答案 0 :(得分:0)

我设法通过删除上下文中未解析的GetType()来获取它:

ZipArchiveEntryType.GetProperty("FullName").GetValue(new ArrayList((ICollection)ZipArchiveType.GetProperty("Entries").GetValue(UnzipInstance)).ToArray()[11])