2016-09-28 72 views
3

我的“嵌入互操作类型”的Netwonsoft.Json库的属性设置为true并返回一个错误:可以将Json.Net嵌入到可执行文件中吗?

Cannot embed interop types from assembly 
'c:\path\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll' 
because it is missing either the 'ImportedFromTypeLibAttribute' attribute or 
the 'PrimaryInteropAssemblyAttribute' attribute 
c:\path\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll 

它看起来像在寻找失踪的Newtonsoft.Json库中的引用,但我不能完全肯定。可以将Json.Net嵌入到可执行文件中吗?

回答

3

你没有说你使用哪种语言,但这里是你如何做到这一点的C#


首先,关闭“嵌入互操作类型”

然后,主可执行项目,卸载和编辑的.csproj文件,并以下线以下:

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> 

这个XML添加到项目文件,保存,并加载它回来了。

<Target Name="AfterResolveReferences"> 
    <ItemGroup> 
    <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'"> 
     <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName> 
    </EmbeddedResource> 
    </ItemGroup> 
</Target> 

然后,您将添加一个新的代码文件,主要项目上,并添加以下代码到它(修改,以适应您的应用程序是如何命名/结构,在WPF应用程序的好地方把它将App.xaml.cs):

[STAThread] 
public static void Main() 
{ 
    AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly; 

    App.Main(); // Run WPF startup code. 
} 

private static Assembly OnResolveAssembly(object sender, ResolveEventArgs e) 
{ 
    var thisAssembly = Assembly.GetExecutingAssembly(); 

    // Get the Name of the AssemblyFile 
    var assemblyName = new AssemblyName(e.Name); 
    var dllName = assemblyName.Name + ".dll"; 

    // Load from Embedded Resources - This function is not called if the Assembly is already 
    // in the same folder as the app. 
    var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(dllName)); 
    if (resources.Any()) 
    { 

     // 99% of cases will only have one matching item, but if you don't, 
     // you will have to change the logic to handle those cases. 
     var resourceName = resources.First(); 
     using (var stream = thisAssembly.GetManifestResourceStream(resourceName)) 
     { 
      if (stream == null) return null; 
      var block = new byte[stream.Length]; 

      // Safely try to load the assembly. 
      try 
      { 
       stream.Read(block, 0, block.Length); 
       return Assembly.Load(block); 
      } 
      catch (IOException) 
      { 
       return null; 
      } 
      catch(BadImageFormatException) 
      { 
       return null; 
      } 
     } 
    } 

    // in the case the resource doesn't exist, return null. 
    return null; 
} 

最后,确保你的主要应用是对刚刚添加的项目的主要方法更新目标方法

来源:http://www.paulrohde.com/merging-a-wpf-application-into-a-single-exe/

相关问题