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 answers
Related Questions in C#
- How to call a C language function from x86 assembly code?
- What does: "char *argv[]" mean?
- User input sanitization program, which takes a specific amount of arguments and passes the execution to a bash script
- How to crop a BMP image in half using C
- How can I get the difference in minutes between two dates and hours?
- Why will this code compile although it defines two variables with the same name?
- Compiling eBPF program in Docker fails due to missing '__u64' type
- Why can't I use the file pointer after the first read attempt fails?
- #include Header files in C with definition too
- OpenCV2 on CLion
- What is causing the store latency in this program?
- How to refer to the filepath of test data in test sourcecode?
- 9 Digit Addresses in Hexadecimal System in MacOS
- My server TCP doesn't receive messages from the client in C
- Printing the characters obtained from the array s using printf?
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 diagnostics reported through CompilationAnalysisContext.ReportDiagnostic do not show up in Visual Studio
- C# CodeAnalysis can't compile code with dynamic keyword
- Unit test C# source generator to emulate a user changing source code?
- Checking project configuration in Roslyn analyzer
- Visual Studio 2022: Impossible to install a VSIX extension from 'Analyzer with Code Fix (.NET Standard)' project template
- In c# code cleanup, How to stop visual studio 2022 adding comments /* Unmerged change from project 'xxxx (net6.0)'
- Code analysis only shows CSxxx and IDExxx notes I see no CAxxx messages
- Why Rider does not highlight some warnings in C#?
- Roslyn Analyzer: How to handle a side effect of renaming classes
- NET Analyzers and AnalysisLevel confusion
- Is there a technical reason why code analysis can't figure out that this variable has been set?
- Roslyn workspace API not loading properly for a third-party solution
- How to hide Visual Studio squiggly lines from analyzers suppressed by a DiagnosticSuppressor
- Set a value to a field in a compiled assembly from an object that exists outside the compiled assembly
- Speed up Roslyn solution analyser
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#
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?
Popular Tags
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)
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.