Как декомпилировать dll в visual studio
Я потерял решение библиотеки классов, могу ли я открыть файл .dll , созданный class-library .
Выполните следующие шаги.
- Перейдите в меню «Пуск».
- Введите Visual Studio Tool.
- Перейдите в указанную папку.
- Нажмите "Командная строка разработчика для VS 2013" в случае VS 2013 или просто «Командная строка Visual Studio» в случае VS 2010.
- После загрузки командной строки на экране типа ILDASM.EXE нажмите клавишу ВВОД.
- Откроется окно ILDASM. Перетащите файл .dll в окно из вашей папки. Или нажмите File->New . Затем добавьте необходимые .dll файл.
- После выполнения вышеуказанных шагов появится файл Mainfest и .dll. Дважды щелкните по этим файлам, чтобы увидеть, что в них содержится.
Перейдите в раздел "Просмотр" и нажмите "Надстройки",
В окне надстроек нажмите Добавить .
Тогда найдите dll, который вы скачали
FileGenerator.dll (с плагином FileGenerator),
Затем закройте окно надстроек.
Перейдите в «Файл», нажмите «Открыть» и выберите DLL, которую хотите декомпилировать,
После того, как вы откроете его, он появится в виде дерева,
Перейдите в Инструменты и нажмите Создать файлы (Crtl + Shift + G),
выберите выходной каталог и выберите соответствующие настройки по своему желанию, Нажмите «Создать файлы».
ИЛИ
Откройте файл .dll в Visual Studio. Или редактор ресурсов.
Вы не можете получить точный код, но вы можете получить его декомпилированную версию.
«Просто декомпиляция» Telerik - лучшее, что я использовал. Это бесплатно, как только вы зарегистрируетесь с электронной почтой.
*. dll файлы - это архивные файлы, открытые с помощью winzip /7zip и т. д. Это не означает, что все файлы .dll являются архивами, вы можете сохранить что угодно с расширением .dll, однако большинство файлов .dll Windows создаются как архивные примеры. Это windows> twain_32.dll, который является архивным файлом, однако twain.dll - это не так, если вы посмотрите на twain.dll, вы увидите MZŽ в качестве первых трех символов блокнота, обозначающих файл /программу скомпилированного C или часть программы. В то время как MZ кажется архивом.
Кроме того, большинство файлов .exe представляют собой архивы, в основном содержащие изображение значка и т. д. для файла и пакетов установщика Windows, а также они содержат всю информацию, необходимую программе для запуска изображений, фильмов и т. д., а также каталоги, включая информацию об установке и текстовый файл. ,
У меня есть игра game.exe, и она содержит файлы классов java и указатель, указывающий .exe запустить файл .bat. Очевидно, что ваш файл .bat будет выполнять вызов javac из архива и запускать игру. Также есть несколько архивов .dll, содержащих файлы классов java.
стандартное перенаправление значка здесь .ico - это файл изображения в файле .dll в файле .exe. Таким образом, изображение в файле .exe является логотипом minecraft. Это в файле с именем autorun.inf. Второй пример
Этот размер файла будет меньше исходного файла того же содержимого. Однако размер файла больше, что говорит о том, что файл действительно был зашифрован. Вероятно, чтобы люди перестали читать их код. В результате чтение содержимого .dll называется расшифровкой, а не декомпиляцией. Декомпиляция преобразует уже скомпилированные текстовые файлы в нечитаемый байт-код. Использование стандартных файлов .dll по определению не является открытым исходным кодом, поскольку включает в себя преднамеренное запутывание байтового кода.
Generate source code
No symbols loaded
The following illustration shows the No Symbols Loaded message.
Source not found
The following illustration shows the Source Not Found message.
Generate and embed sources for an assembly
Extract and view the embedded source code
You can extract source files that are embedded in a symbol file using the Extract Source Code command in the context menu of the Modules window.
The extracted source files are added to the solution as miscellaneous files. The miscellaneous files feature is off by default in Visual Studio. You can enable this feature from the Tools > Options > Environment > Documents > Show Miscellaneous files in Solution Explorer checkbox. Without enabling this feature, you won't be able to open the extracted source code.
Extracted source files appear in the miscellaneous files in Solution Explorer.
Known limitations
Requires break mode
Generating source code using decompilation is only possible when the debugger is in break mode and the application is paused. For example, Visual Studio enters break mode when it hits a breakpoint or an exception. You can easily trigger Visual Studio to break the next time your code runs by using the Break All command ().
Decompilation limitations
Debug optimized or release assemblies
When debugging code that was decompiled from an assembly that was compiled using compiler optimizations, you may come across the following issues:
- Breakpoints may not always bind to the matching sourcing location.
- Stepping may not always step to the correct location.
- Local variables may not have accurate names.
- Some variables may not be available for evaluation.
Decompilation reliability
A relatively small percentage of decompilation attempts may result in failure. This is due to a sequence point null-reference error in ILSpy. We have mitigated the failure by catching these issues and gracefully failing the decompilation attempt.
Limitations with async code
The results from decompiling modules with async/await code patterns may be incomplete or fail entirely. The ILSpy implementation of async/await and yield state-machines is only partially implemented.
More details can be found in the GitHub issue: PDB Generator Status.
Just My Code
The Just My Code (JMC) settings allows Visual Studio to step over system, framework, library, and other non-user calls. During a debugging session, the Modules window shows which code modules the debugger is treating as My Code (user code).
Decompilation of optimized or release modules produces non-user code. If the debugger breaks in your decompiled non-user code, for example, the No Source window appears. To disable Just My Code, navigate to Tools > Options (or Debug > Options) > Debugging > General, and then deselect Enable Just My Code.
Extracted sources
Source code extracted from an assembly has the following limitations:
- The name and location of the generated files isn't configurable.
- The files are temporary and will be deleted by Visual Studio.
- The files are placed in a single folder and any folder hierarchy that the original sources had isn't used.
- The file name for each file contains a checksum hash of the file.
Создание исходного кода
Символы не загружены
Исходный код не найден
Создание и внедрение исходного кода для сборки
Извлечение и просмотр внедренного исходного кода
Исходные файлы, внедренные в файл символов, можно извлечь с помощью команды Извлечь исходный код в контекстном меню окна Модули.
Извлеченные исходные файлы добавляются в решение как прочие файлы. В Visual Studio функция "Прочие файлы" по умолчанию отключена. Чтобы включить эту функцию, установите флажок Инструменты > Параметры > Среда > Документы > Показывать прочие файлы в Обозревателе решений. Без включения этой функции вы не сможете открыть извлеченный исходный код.
Извлеченные исходные файлы отображаются в разделе прочих файлов в Обозревателе решений.
Известные ограничения
Требуется режим прерывания выполнения
Создание исходного кода с помощью декомпиляции возможно только в том случае, если отладчик находится в режиме прерывания выполнения и приложение приостановлено. Например, Visual Studio переходит в режим прерывания, попадая в точку останова или в исключение. Вы можете легко активировать прерывание выполнения Visual Studio при следующем запуске кода с помощью команды Прервать все ().
Ограничения декомпиляции
Отладка оптимизированных сборок или сборок выпуска
При отладке кода, декомпилированного из сборки, которая была скомпилирована с использованием оптимизаций компилятора, вы можете столкнуться со следующими проблемами:
- точки останова могут не всегда быть привязаны к соответствующим исходным расположениям;
- при пошаговом выполнении шаг может не всегда переходить в правильное место;
- имена локальных переменных могут быть неточными;
- некоторые переменные могут быть недоступны для оценки.
Дополнительные сведения можно найти в описании проблемы GitHub Интеграция ICSharpCode.Decompiler с отладчиком VS.
Надежность декомпиляции
Относительно небольшой процент попыток декомпиляции может привести к сбою. Это происходит из-за ошибки пустой ссылки точки последовательности в ILSpy. Мы устранили этот сбой путем перехвата таких проблем и корректного завершения попытки декомпиляции.
Дополнительные сведения можно найти в описании проблемы GitHub Интеграция ICSharpCode.Decompiler с отладчиком VS.
Ограничения при работе с асинхронным кодом
Результаты декомпиляции модулей с шаблонами кода async/await могут быть неполными или неудачными в целом. Шаблоны кода async/await и машины состояния yield state-machine в ILSpy реализованы только частично.
Дополнительные сведения можно найти в описании проблемы GitHub Состояние генератора PDB.
Только мой код
Параметры режима Только мой код (JMC) позволяют Visual Studio выполнять шаг с обходом системы, платформы, библиотеки и других вызовов непользовательского кода. Во время сеанса отладки в окне Модули отображаются модули кода, которые отладчик воспринимает как "Мой код" (т. е. пользовательский код).
При декомпиляции оптимизированных модулей или модулей выпуска создается непользовательский код. Если отладчик прерывается в декомпилированном непользовательском коде, появляется окно Отсутствует источник. Чтобы отключить режим "Только мой код", перейдите в раздел Инструменты > Параметры (или Отладка > Параметры) > Отладка > Общие и снимите флажок Включить только мой код. .
Извлеченный исходный код
Исходный код, извлеченный из сборки, имеет следующие ограничения.
- Имена и расположение созданных файлов нельзя настроить.
- Файлы являются временными и будут удалены Visual Studio.
- Файлы помещаются в одну папку без использования какой-либо иерархии, которая была в оригинальных исходных файлах.
- Имя каждого файла содержит хэш контрольной суммы файла.
We have recently released a new decompilation and symbol creation experience in the latest preview of Visual Studio 2019 version 16.5 that will aid debugging in situations where you might be missing symbol files or source code. As we launch this feature, we want to ensure that we are creating the most intuitive workflows so please provide feedback.
Decompilation and PDB generation with ILSpy
Decompilation is the process used to produce source code from compiled code. In order to accomplish this we are partnering with ILSpy, a popular open source project, which provides first class, cross platform symbol generation and decompliation. Our engineering team is working to integrate ILSpy technology into valuable debugging scenarios.
What are symbol files? Why do you need them?
Debuggers are able to use the information in the symbol file to determine the source file and line number that should be displayed, and the location in the executable to stop at when you set a breakpoint. Debugging without a symbol file would make it difficult to set breakpoints on a specific line of code or even step through code.
By integrating decompilation directly into your debugging experiences we hope to provide developers with the most direct route to troubleshooting issues in 3 rd party managed code. We are initially integrating the decompilation experiences into the Module Window, No Symbols Loaded, and Source Not Found page.
No Symbols Loaded/Source Not Found
There are a several ways in which Visual Studio will try to step into code for which it does not have symbols or source files available:
- Break into code from a breakpoint or exception.
- Step into code.
- Switch to a different thread.
- Change the stack frame by double-clicking a frame in the Call Stack window.
Under these circumstances, the debugger displays the No Symbols Loaded or Source Not Found page and provides an opportunity to load the necessary symbols or source.
In the following example I have opened a crash dump in Visual Studio and have hit an exception in framework code. I do not have the original source code so If I try to switch to the main thread, I see the No Symbols Loaded page. However, it is now possible to decompile the code directly on this page and see the origins of the exception.
Module Window
During debugging the Modules window is a great place to get information related to the assemblies and executables currently in memory. To open the Modules window, select Debug > Windows > Modules.
Once you have identified a module that requires decompilation, you can right-click on the module and select “Decompile Source to Symbol File”. This action creates a symbol file containing decompiled source which in turn permits you to step into 3 rd party code directly from your source code.
It will also be possible to extract source code to disk by right clicking on a module with embedded source and clicking “Extract Embedded Source”. This process exports source files to a Miscellaneous files folder for further analysis. In the following example I open an extracted .cs file and set a break point to better understand the 3rd party code I am using.
Some Considerations
- Decompiled source does not always resemble the original source code. Decompilation is best used to understand how the program is executing and not as a replacement for the original source code.
- Debugging code that was decompiled from an assembly that was built using compiler optimizations may encounter the following issues:
- Breakpoints not always binding to the matching sourcing location
- Stepping may not always step to the correction
- Async/await and yield state-machines may not be fully resolved
- Local variables may not have accurate names
- Some variables may not be able to be evaluated in the IL Stacks is not empty
- The name and location of the generated files is not configurable.
- They are temporary and will be deleted by Visual Studio.
- Files are placed in a single folder and any folder hierarchy that the original sources had is not used.
- The file name for each file has a checksum hash of the file.
Try it now!
Download the preview and try out decompilation and let us how it works for you! Please reach out and give us feedback over at Developer Community. Finally, we also have a survey for collecting feedback on the new experiences here. We look forward to hearing from you.
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I have a DLL file which I would like to decompile in order to edit the source code. Does anyone have any idea of how I come go about doing this?
I don not have the original solution (The person who wrote it has left the company)
Answers
- Open up the Reflector.exe,
- Go to View and click Add-Ins,
- In the Add-Ins window click Add.
- Then find the dll you have downloaded FileGenerator.dll (witch came wth the FileGenerator plugin),
- Then close the Add-Ins window.
- Go to File and click Open and choose the dll that you want to decompile,
- After you have opend it, it will appear in the tree view,
- Go to Tools and click Generate Files (Crtl+Shift+G),
- select the output directory and select appropriate settings as your wish,
- Click generate files.
Reply if success,
Thanks & Good luck!
Thanks for the post,
Reply if success.
All replies
Thanks for the post,
Reply if success.
- Open up the Reflector.exe,
- Go to View and click Add-Ins,
- In the Add-Ins window click Add.
- Then find the dll you have downloaded FileGenerator.dll (witch came wth the FileGenerator plugin),
- Then close the Add-Ins window.
- Go to File and click Open and choose the dll that you want to decompile,
- After you have opend it, it will appear in the tree view,
- Go to Tools and click Generate Files (Crtl+Shift+G),
- select the output directory and select appropriate settings as your wish,
- Click generate files.
Reply if success,
Thanks & Good luck!
Thanks a mill. The above was a GREAT Success. :-)
You are most welcome !.
Does anyone know if this is because the plugin is not compatible with the beta? Or is it that the plugin does not even work with their newest version, version 7 because when this thread was created I believe they were not using version 7.
I have tried downloading older versions off of .cnet, but when you run the reflector.exe a message pops up saying newer version available would you like to download it. If you choose no it removes the .exe if you choose yes it says you must visit the website to download (to pay) and then it deletes the .exe.
Thanks for any help on this
Something else I am wondering:
Seems there is actual error output:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. (ReflectionTypeLoadException)
LoaderExceptions:
Could not load file or assembly 'Reflector, Version=5.0.0.0, Culture=neutral, PublicKeyToken=18ca6bb8dd6a03c3' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (FileLoadException)That error message repeats 7 more times.
couple of hours of searching I found free stable version 6.5
I downloaded it and tried to use the plugin. Seems to be working. I think the problem might be the fact that version 7 is in beta. Hopefully the problem doesn't exist in final production of version 7.
Cheers! Hope this helps someone else
*edit edit edit edit*
Читайте также: