简体   繁体   中英

How to create an Assembly (CSharpCompilation) from an existing Assembly in Roslyn?

In .NET Framework 4.8, i could use AssemblyBuilder to create a new Assembly based on an existing Assembly, add some further modifications (such as encryption) and save it as a new.dll with AssemblyBuilder.Save().

In .NET 6, they removed the functionality to save an Assembly to file, along with other methods i used.

As an alternative i looked into Roslyn and how to generate Assemblies. The thing is, that i don't have the source code i want to compile into a new Assembly, but only an already compiled Assembly i want to modify.

My use case would look like this:

private void Protect(FileInfo dllSourceFile, FileInfo targetFile) {
    Assembly assembly = Assembly.LoadFrom(dllSourceFile.FullName);
    CSharpCompilation compilation = CSharpCompilation.Create(assembly);
    //...modify compilation, encrypt files
    var result = compilation.Emit(targetFile.FullName);
}

Is there any functionality in Roslyn (or.Net 6) that helps me here? Even better if it directly uses AssemblyBuilder instead of Assembly.

It is not possible to use Roslyn to modify an already compiled assembly and save the modified version to a new file. Roslyn is a set of APIs for working with C# and VB.NET source code, and it does not provide any functionality for modifying compiled assemblies.

One way you could achieve the goal of modifying an already compiled assembly is to use reflection to load the assembly into memory, make the desired modifications using the reflection API, and then use a tool like ILSpy or dnlib to save the modified assembly to a new file. However, this approach is likely to be more complex and error-prone than using AssemblyBuilder, which was specifically designed for this purpose.

Alternatively, you could consider using a different tool or library that provides the ability to modify compiled assemblies. Some options you might consider include Mono.Cecil or Fody.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM