I'm developing an application that detects and eliminates useless external references in a given C# project for example a package referenced but not used. For this I need to enumerate all assemblies used either at compile and runtime. For those used at a runtime, I can get names using reflection specifically calling Assembly.GetReferencedAssemblies(). But for those used only at compile-time I think that there is no way to list them without using Roslyn. Have you please any answers to my problematic?
Is there a method or a way in Roslyn to enumerate all assemblies used at compile time by a given C# project
1.4k Views Asked by Tahatoun At
1
There are 1 best solutions below
Related Questions in C#
- Passing arguments to main in C using Eclipse
- kernel module does not print packet info
- error C2016 (C requires that a struct or union has at least one member) and structs typedefs
- Drawing with ncurses, sockets and fork
- How to catch delay-import dll errors (missing dll or symbol) in MinGW(-w64)?
- Configured TTL for A record(s) backing CNAME records
- Allocating memory for pointers inside structures in functions
- Finding articulation point of undirected graph by DFS
- C first fgets() is being skipped while the second runs
- C std library don't appear to be linked in object file
- gcc static library compilation
- How to do a case-insensitive string comparison?
- C programming: Create and write 2D array of files as function
- How to read a file then store to array and then print?
- Function timeouts in C and thread
Related Questions in ASSEMBLIES
- Details on how to handle AppDomain.AssemblyResolve event properly upon updating the needed assembly
- Right way to generate shared code in source generators
- How do I use assemblies with PowerShell JEA?
- .Net Framework 4 site compilation error due to loading too many assembly (dll) files. "CS1647: An expression is too long or complex to compile"
- "FileNotFoundException: Could not find System.Private.CoreLib.dll" in Release-mode MAUI application
- NAudio - Could not load an assembly or one of its dependencies: Naudio.Core
- How to force visual studio to automatically increase the build number?
- Difference between PowerShell 5.1 and 7 when working with certificates
- Get class that implements an interface across multiple .NET assemblies
- C# Where are these assembly references coming from?
- .Net Core looking for a lower version of referenced assembly
- Can I use asm() in C instead of asm?
- Codebase lists wrong path for referenced assemblies
- Can digital signing of 3rd party DLLs in nuget packages have potential negative effects?
- Issue Publishing Power BI Paginated Report with Custom Assembly for QR Code Generation
Related Questions in ROSLYN
- Source generators get the referencing project path - retrieve useful value from IncrementalValueProvider<string>
- Roslyn diagnostics reported through CompilationAnalysisContext.ReportDiagnostic do not show up in Visual Studio
- Using Roslyn and .NET Core : how do I resolve "type or namespace name "Forms" does not exist in the namespace 'System.Windows'
- Sharing runtime assembly in C# Roslyn script
- Detecting unused using statements with Roslyn
- Roslyn generated dll can't be referenced
- Memory Leak caused by Roslyn, how do I contain it?
- How to use Roslyn in wpf application
- Roslyn INamedTypeSymbol.ContainingNamespace.Name an empty string
- Add System.Text.Json to incremental source generator
- No CS0184 warning for impossible check
- Enforce Code Cleanup code-style that is not available in editorconfig
- How to execute Roslyn fixers that rely on internal interfaces
- C# runtime compilation complains The type 'Object' is defined in an assembly that is not referenced
- Dotnet build is using old version of IIncrementalGenerator
Related Questions in ROSLYN-CODE-ANALYSIS
- Roslyn Rewrite Method Calls to use await Modifier
- Visual Studio 2015 Package Extension,referenced dll not copied
- Could not load type 'System.Reflection.Metadata.ISignatureTypeProvider from assembly System.Reflection.Metadata
- How to get underlying type for IEnumerable<T> with Roslyn?
- Finding location of all references across solution
- How to add XML Comments to a MethodDeclarationSyntax node using Roslyn?
- Constructing NameOf expression via SyntaxFactory (Roslyn)
- Finding all not inheriting C# classes with Roslyn and changing to inheriting from base object (java-like)
- Masstransit Analyzers
- Not getting a namespace/reference in CSharpCompilation .net Core
- Roslyn: detect when a local variable has been declared with `using`
- Speed up Roslyn solution analyser
- How to hide Visual Studio squiggly lines from analyzers suppressed by a DiagnosticSuppressor
- Roslyn workspace API not loading properly for a third-party solution
- Is there a technical reason why code analysis can't figure out that this variable has been set?
Related Questions in EXTERNAL-ASSEMBLIES
- Why adding external dll in class library expected to be added in calling project?
- Is there a method or a way in Roslyn to enumerate all assemblies used at compile time by a given C# project
- c# How to programmatically load external assemblies with the same namespace
- Can't load System.Web.Mvc even though it's clearly there and is correct version
- How to activate breakpoints in a single DLL in Visual Studio when the program is not started via Visual Studio
- Using Ninject to inject IJob from external assembly into Quartz.net scheduler
- Where .NET Assembly loaded from CodeBase goes?
- Chain-referenced assemblies in WPF
- mvc3 razor page don't find Namespace
- Using Ninject with MVC3 controllers that are in external assemblies
- How can the Visual Studio build output location be specified for referenced assemblies?
- DLL works for web based apps but not stand window apps
- How do I handle dependency DLLs that aren't referenced by my code but are required to be in the bin?
- .NET Assembly Referencing 101
- Serializing and Deserializing External Assembly in C#
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
This is just a simple approach, far from perfect. I am sure you can go deeper and play around with Roslyn as much as you want. I am also sure there are much better experts on compilers and Roslyn out there than me :)
Note that this approach does not handle dynamically loaded assemblies. It avoids running the project.
Referenced assemblies
You can use an XML parser instead of Roslyn to analyze the project or solution file. There you will find the list of all referenced packages and project, e.g.:
The above example comes from a .NET Core 3.1 project file.
Update
In order to collect transitive dependencies as well there are several options.
For .NET Core projects you may call
dotnet restoreand then read the following file$ProjectFolder/obj/project.assets.json. It is a json file that contains all references that were resolved containing both NuGet and runtime packages.If you want to avoid restoring the project/solution you can start with the packages found in
.csprojas described above and use the NuGet Server API to get an array of dependencies for each. Doing this recursively will yield the same result asdotnet restore. NuGet Core wraps the API as C# classes so you can call it directly from your code. Dependencies can be easily queried like here: How to get the dependencies of a NuGet package from private NuGet feed?Required assemblies
Now you need to identify those that are really necessary. The compilation process takes care of that. It does not (to my humble knowledge) insert any unnecessary references into the compiled code.
Roslyn semantic model
Addressed in this question: Roslyn getting dependencies for class
IL option
You can use Roslyn to compile the given project, then load the generated IL and look for references like
[System.Private.CoreLib]. Just throw all referenced assemblies into aHashSetand remove them once you find a matching call in the IL. The resulting set will contain the references that can be removed.Maybe this project can help viewing the IL. Also SharpLab can be very handy when you need Roslyn output examples.
Load option
If you are fine with loading the compiled project, you can use
Assembly.GetReferencedAssemblies()as you indicated in the question instead of analyzing the IL.