Could not load file or assembly system windows forms

Have problems with Visual Studio 2019, where I have created a solution with 2 projects. The start-up project (# 1) has been created with the Console App (.NETCore) as a base. The second project (# 2) is based on the Windows Forms app (.NET Framework)
 

Have problems with Visual Studio 2019, where I have created a solution with 2 projects. The start-up project (# 1) has been created with the Console App (.NETCore) as a base. The second project (# 2) is based on the Windows Forms app (.NET
Framework)

Project 1 contains the main logic and calls a procedure in project 2 that will set up a form, take care of specified values ​​and return this via global variables. Both projects do their jobs separately. It is when it comes to the call
that errors occur. The call has been adapted as the initial syntax error occurred which has now been corrected so compilation of the solution is error free and without warnings. When executed, there is an interruption

System.IO.FileNotFoundException:
‘Could not load file or assembly ‘System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′. Det går inte att hitta filen.’

This means that it is not possible to track in the program as I wanted. Of course, there are differences in the two projects’ .NET environments that make up for it, but it is not told how I can get hold of the missing file.

Question 1. Does anyone know how to get the file and how it is then incorporated into the environment?

I am not a VB encoder so that with Objects, classes, methods etc. is not something I have immersed myself in. However, I can do so much that I can make it work as regular calls with arguments and so on.

The call itself is simple in itself and I think I got to that with how to send the information. However, I do not find anywhere the values ​​that the parameters should contain.

Call MYform1.Form1_Load(Mysender, Myargs)

Question 2. Does anyone know how to find which values ​​should be included in the Mysender and Myargs parameters

In the log I find this

‘Project20200727.exe’ (CoreCLR: DefaultDomain): Loaded ‘C:Program FilesdotnetsharedMicrosoft.NETCore.App3.1.6System.Private.CoreLib.dll’.

‘Project20200727.exe’ (CoreCLR: clrhost): Loaded ‘C:UsersjannesourcereposProject20200727binDebugnetcoreapp3.1Project20200727.dll’. Symbols loaded.

‘Project20200727.exe’ (CoreCLR: clrhost): Loaded ‘C:Program FilesdotnetsharedMicrosoft.NETCore.App3.1.6System.Runtime.dll’.

‘Project20200727.exe’ (CoreCLR: clrhost): Loaded ‘C:UsersjannesourcereposProject20200727binDebugnetcoreapp3.1WindowsApp3_20200730.exe’. Symbols loaded.

An unhandled exception of type ‘System.IO.FileNotFoundException’ occurred in Unknown Module.

Could not load file or assembly ‘System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’. Det går inte att hitta filen.

The program ‘[13828] Project20200727.exe’ has exited with code -1 (0xffffffff).

Best regards

Janne

  • Moved by

    Friday, July 31, 2020 2:02 AM

@bnlakshmibn

.Net core issue with some System reference libraries

Hi,
I am trying to create a .net core Web api. I had added my logic there. But while trying to run that, I am getting the exception as Could not load file or assembly ‘System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)

This kind of exception is happening with many «System.» assemblies.

@seriouz

Yeah you cannot use dotnet core for WinForms!
You have to use FullFramework.

@Petermarcu

Looks like you need to figure out what is bringing in the System.Windows.Forms dependency. What is your TargetFramework? What are the other System assemblies?

@joshfree

Closing this old issue. Feel free to re-open this with more information.

@lindexi

I start up my application that throw BadImageFormatException

System.BadImageFormatException: 未能加载文件或程序集“System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”或它的某一个依赖项。该模块应包含一个程序集清单。
文件名:“System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”

@patillaxmi123

i am also facing the same issue when i try to call the .net core 3.0 api to windows workflow foundation.
getting following issue.
BadImageFormatException: Could not load file or assembly ‘System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (0x80131058)
Microservices.Controllers.WWFController.Get(int age) in WWFController.cs, line 31

Please help on this

@ChahatKumar

@seriouz Hey , i am trying to use winforms for .net Core console app.
Is there any documentation for the same that it is not possible for .NET CORE

The same referencing and code works smooth on .NET FRAMEWORK

@seriouz

@ChahatKumar

@ChahatKumar Try it with dotnet 5.

Thanks ! I tried using this but I find that a dotnet 5 console app cannot produce both the form and console window ?right?

@seriouz

No i don’t think you can run a console app as WinForms app. Why do you need a console app in the first place?

@ChahatKumar

I basically have a library written as a console app which I plan to release.
But for collection of user data I need a contest frok the user for the same for which I was planning to add a form.

Altho this is possible in a. . Net Framework console app, but I am unsure since a similar procedure didn’t work for. NET CORE

My whole library is written in. NET CORE

@seriouz

Try this in your csproj. It should keep the console window open of a winforms app.

<PropertyGroup>
  <OutputType>Exe</OutputType>
</PropertyGroup>

@ChahatKumar

Hi , it did work .. Thanks !
But now giving an error that a dll is not connected ..

Just wanted to cofirm one thing -> for dll’s like System.Windows.Forms -> i referenced them using my internal program files where they are present and added path in .csproj

If i add through COM reference , it gives error and doesn’t load ( in case of .net Core app)

I wasnt able to find document for winforms in .NET CORE solving my issue
Am i referencing them the right way ?

Thannks and apologies for the out of topic doubt

@seriouz

Yes, reference the Packages in your .csproj. Dlls you have to reference like this:

<ItemGroup>
  <Reference Include="YourAssembly">
    <HintPath>Path/To/YourAssembly.dll</HintPath>
  </Reference>
</ItemGroup>

@ChahatKumar

  • #1

I get this error when trying to run the code

using System;
using System.Threading;
namespace cTest
{
class Program
{
public static int Base = 0x004E4DBC;
        public static int Health = 0xF4;

static void Main(string[] args)
{
            VAMemory vam = new VAMemory("ac_client");
            int LocalPlayer = vam.ReadInt32((IntPtr)Base);
            while (true)
{
int address = LocalPlayer + Health;
                vam.WriteInt32((IntPtr)address, 9999);

                Thread.Sleep(100);

            }

        }
}
}

Activated Event Time Duration Thread
Exception thrown: ‘System.IO.FileNotFoundException’ in VAMemory.dll («Could not load file or assembly ‘System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’. The system cannot find the file specified.») Exception thrown: ‘System.IO.FileNotFoundException’ in VAMemory.dll («Could not load file or assembly ‘System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’. The system cannot find the file specified.») Hyperlink: Activate Historical Debugging 0.14s [13308] Main Thread

Trying to use Database Compare capability of Office 2013 Professional Pro.  Complete text of error message: follows

************** Exception Text **************

System.IO.FileNotFoundException: Could not load file or assembly ‘Microsoft.ReportViewer.WinForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’
or one of its dependencies. The system cannot find the file specified.

File name: ‘Microsoft.ReportViewer.WinForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’

   at ProdianceAccessManager.CompareReport.InitializeComponent()

   at ProdianceAccessManager.CompareReport..ctor(String rootFolder, ListView resultList, Boolean brief, String file1, String file2, Boolean compareTables,
Boolean compareQueries, Boolean compareModules, Boolean compareMacros, Boolean compareForms, Boolean compareReports, Boolean comparePages, Dictionary`2 itemPathDictionary)

   at ProdianceAccessManager.AccessCompare.btnCompare_Click(Object sender, EventArgs e)

   at System.Windows.Forms.Control.OnClick(EventArgs e)

   at System.Windows.Forms.Button.OnClick(EventArgs e)

   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)

   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)

   at System.Windows.Forms.Control.WndProc(Message& m)

   at System.Windows.Forms.ButtonBase.WndProc(Message& m)

   at System.Windows.Forms.Button.WndProc(Message& m)

   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)

   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)

   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

WRN: Assembly binding logging is turned OFF.

To enable assembly bind failure logging, set the registry value [HKLMSoftwareMicrosoftFusion!EnableLog] (DWORD) to 1.

Note: There is some performance penalty associated with assembly bind failure logging.

To turn this feature off, remove the registry value [HKLMSoftwareMicrosoftFusion!EnableLog].

************** Loaded Assemblies **************

mscorlib

    Assembly Version: 4.0.0.0

    Win32 Version: 4.0.30319.18444 built by: FX451RTMGDR

    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll

—————————————-

DatabaseCompare

    Assembly Version: 5.5.0.5

    Win32 Version: 5.5.0.5

    CodeBase: file:///C:/Program%20Files%20(x86)/Microsoft%20Office/Office15/DCF/DATABASECOMPARE.EXE

—————————————-

System.Windows.Forms

    Assembly Version: 4.0.0.0

    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL

    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll

—————————————-

System.Drawing

    Assembly Version: 4.0.0.0

    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL

    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll

—————————————-

System

    Assembly Version: 4.0.0.0

    Win32 Version: 4.0.30319.34238 built by: FX452RTMGDR

    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll

—————————————-

System.Configuration

    Assembly Version: 4.0.0.0

    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL

    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll

—————————————-

System.Xml

    Assembly Version: 4.0.0.0

    Win32 Version: 4.0.30319.34234 built by: FX452RTMGDR

    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll

—————————————-

Accessibility

    Assembly Version: 4.0.0.0

    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL

    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/Accessibility/v4.0_4.0.0.0__b03f5f7f11d50a3a/Accessibility.dll

—————————————-

Common.FileUtils

    Assembly Version: 5.5.0.5

    Win32 Version: 5.5.0.5

    CodeBase: file:///C:/Program%20Files%20(x86)/Microsoft%20Office/Office15/DCF/Common.FileUtils.DLL

—————————————-

************** JIT Debugging **************

To enable just-in-time (JIT) debugging, the .config file for this

application or computer (machine.config) must have the

jitDebugging value set in the system.windows.forms section.

The application must also be compiled with debugging

enabled.

For example:

<configuration>

    <system.windows.forms jitDebugging=»true» />

</configuration>

When JIT debugging is enabled, any unhandled exception

will be sent to the JIT debugger registered on the computer

rather than be handled by this dialog box.

Microsoft Windows [Version 6.1.7601]

Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

У меня есть решение с одним файлом проекта. Я использую приложение ClickOnce. Все работает отлично и хорошо на моем компьютере, но когда я пытаюсь запустить его на кого-то другого, я получаю эту ошибку.

System.IO.FileNotFoundException: Could not load file or assembly 'System.Windows.Forms.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Windows.Forms.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

System.Windows.Forms.DataVisualization находится в фасете, загруженном в качестве ссылки в моем проекте, и я считаю, что там должно быть удобно использовать утверждения, где бы он ни использовался.

Когда я перехожу в свой проект «Свойства» > «Опубликовать» > «Файлы приложений»… System.Windows.Forms.DataVisualization имеет рядом с ним восклицательный знак, в котором текст всплывающей подсказки «Этот элемент больше не ссылается на проект. больше не требуется, его можно удалить, щелкнув правой кнопкой мыши на элементе». статус публикации — «Включить», а «Хеш» — «Включить». статус публикации не является, однако, «Include (auto)»; Exclude имеет автотекст рядом с ним. Но я включаю или исключаю, что получаю ту же ошибку при работе на ком-то машине.

Как вы думаете, что мне нужно сделать, чтобы этот файл правильно ссылался?

Спасибо

Update:

Я попытался установить Local Copy = true, построить перестройку безрезультатно.

Теперь я расскажу о других предложениях. (Это долгая прогулка между мной и компьютером, которая не работает!)

Вопрос:

Я получаю FileNotFoundException в проекте приложения Windows Forms со следующим сообщением:

Could not load file or assembly 'System.Drawing, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
The system cannot find the file specified.

Чтобы воспроизвести проблему:

  • Выберите “Создать”, “Проект”, выберите .Net Framework 2.0 в качестве цели и выберите “Приложение Windows Forms” в качестве типа проекта.
  • В свойствах формы, созданной по умолчанию, выберите значение свойства Icon. Будет выполнен любой файл .ico. Это вложит файл в файл resx.
  • Скомпилируйте и запустите приложение.

Когда я это делаю, программа останавливается в строке this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); со следующим исключением:

System.IO.FileNotFoundException was unhandled
Message=Could not load file or assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
Source=mscorlib
FileName=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

Я получаю это на Visual Studio 2010 SP1, недавно установленном в Windows 8 Developer Preview. Если я изменю свойства проекта для таргетинга .Net Framework 4, ошибка исчезнет.

В файле Form1.resx я вижу, что версия сборки System.Drawing явно указана как 2.0:

<assembly alias="System.Drawing" name="System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

Любые идеи?

Лучший ответ:

Я нашел возможное решение, попробуйте следующее:

Откройте файл resx в конструкторе и настройте accessmodifier из общедоступного без генерации кода.

Изменить: есть обходной путь, но очень раздражает, хотя.

  • Откройте форму в конструкторе и сделайте необходимые изменения графического интерфейса. Закрыть дизайнер и сохранить
  • Скомпилировать проект и получить ошибку компиляции RESX (только формы с Imagelist должны иметь эту проблему)
  • Дважды щелкните по ошибке компиляции resx, чтобы открыть файл resx.
  • Перейдите в начало imagestream.
  • Отредактируйте верхнюю строку потока изображений:
    AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w
    К
    AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0yLjAuMC4w
  • Закрыть и сохранить файл resx и перекомпилировать.

** ПРИМЕЧАНИЕ. Единственное отличие – это символы в конце “j00LjAuMC4w” на “j0yLjAuMC4w”
Это нужно сделать КАЖДЫЙ РАЗ, вы открываете форму в режиме конструктора.

Microsoft заявляет, что собирается исправить ее в следующей версии VS…

Источник: http://connect.microsoft.com/VisualStudio/feedback/details/532584/error-when-compiling-resx-file-seems-related-to-beta2-bug-5252020

Ответ №1

Это ошибка. Я тоже это видел. Это происходит потому, что ваш файл .resx указывает на 4.0.0.0 версию System.Drawing, где его не существует. Чтобы решить эту проблему, я обычно редактирую .resx в блокноте для изменения 4.0.0.0 до 2.0.0.0. Ошибка указана в следующих точных шагах, которые вы наметили.

Ответ №2

Эта проблема может возникнуть, если .net 4.5 preview resgen используется для создания файлов ресурсов.

У меня такая же проблема на моем ноутбуке (Windows 7, VS2010 Premium, VS11 Developer Preview).
У меня возникла проблема с проектом простых форм, когда я говорю “localizable = true” в форме. В моем случае нет данных изображения. Проект имеет значение .net 3.5

private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.SuspendLayout();
//
// Form1
//
resources.ApplyResources(this, "$this"); //exception Could not load file or assembly 'System.Drawing, Version=4.0.0.0,

Если я затем скопирую этот проект на другой компьютер (Windows 7, VS2010 Premium) и попытаюсь его отладить, ошибка останется.
Ошибка уходит, если я очищаю решение (а не проект) (или удаляю bin/obj вручную)
Если я затем скопирую это решение обратно на свой ноутбук, ошибка исчезнет, ​​но я не могу увидеть форму снова в представлении дизайна 'Error message: at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.EnsureDocument(IDesignerSerializationManager manager)'

Причиной всего этого является версия .net в файлах *.Designer.cs.

  • Версия выполнения: 4.0.30319.239 на компьютере, где он работает,
  • Версия Runtime: 4.0.30319.17020 на ноутбуке, где я получаю исключение.

Может ли кто-нибудь сказать мне, где я могу настроить, какая версия resgen используется при работе с проектами .net 3.5?

Ответ №3

У меня была эта проблема, и мне показалось, что это странно связано с .Net 4.5 beta. Удаление этого и переустановка .Net 4.0 заставила проблему уйти. Не уверен, есть ли способ иметь .Net 4.5 beta и использовать ресурсы из проекта .Net 2.0 одновременно.

Ответ №4

У меня была такая же проблема.

Я отремонтировал .net 4.5.1 и исправил его.

Ответ №5

Недавно у меня было такое же сообщение об ошибке, когда клиент попросил меня понизить приложение.

Использование Visual Studio 2010 Professional Я изменил целевую структуру с .NET Framework 4 на .NET Framework 3.5. Построение с ошибкой завершилось с указанным сообщением об ошибке. Решение заключалось в том, чтобы удалить файл образа, вызывающий проблему из ресурсов приложения. Добавив его снова, версия System.Drawing была указана как 2.0.0.0, а создание выполнено успешно.

Ответ №6

Я столкнулся с той же проблемой, и ни одно из вышеперечисленных предложений не работало для меня, поэтому я сделал следующее:

Откройте проект

Перейти к Обозреватель решений
Развернуть справочную группу
Удалить ссылку System.Drawing
Щелкните правой кнопкой мыши на справочной группе
Добавить ссылку
На вкладке “.NET” найдите System.Drawing, чтобы добавить правильную ссылку

Ответ №7

У меня была такая же проблема.. с моей инфраструктурой 2.0 Project продолжал ссылаться на 4.0 dll. То, как я смог это исправить… просто перейдите к ссылке на проект → выберите “Syste.Drawing” → Свойства и там выберите точную версию = true

Это заставит использовать dll 2.0 framework.

Надеюсь, что это поможет.

Ура!!!

Ответ №8

Я также столкнулся с этой проблемой, и в моем случае причиной было создание двух по существу дублирующих проектов параллельно, один из которых нацеливался на .NET 2.0, а другой – на .NET 4.0, оба из которых содержат в основном один и тот же код и ресурсы. Если бы время было правильным, проект 2.0 собирал выходной файл из проекта 4.0 и в итоге ссылался на библиотеки 4.0.

Я исправил это, построив проекты последовательно, заставив их зависеть от другого.

(Я понимаю, что это, вероятно, не было причиной исходной проблемы, опубликованной @Leonardo, но это может быть полезно для будущих посетителей, которые сталкиваются с этой ошибкой с аналогичной настройкой с двумя проектами.)

Ответ №9

Ответ №10

Это не относится к ситуации OP, но если вы получаете эту ошибку в связи с использованием класса ResourceWriter для преобразования файла .resx файл .resources, тогда читайте дальше. Я столкнулся с этой ошибкой, и единственный способ, которым я "System.Drawing, Version=4.0.0.0" исправить это, – это сканировать данные для "System.Drawing, Version=4.0.0.0" и заменить его "System.Drawing, Version=2.0.0.0". Здесь мой код (это часть модификации Roslyn):

  /// <summary>
/// Method that gets called by ManagedResource.WriteData() in project CodeAnalysis during code
/// emitting to get the data for an embedded .resx file. Caller guarantees that the returned
/// MemoryStream object gets disposed.
/// </summary>
/// <param name="resourceFullFilename">full path and filename for .resx file to embed</param>
/// <param name="targetLessThan4">true if necessary to change System.Drawing from 4.0.0.0 to 2.0.0.0</param>
/// <returns>MemoryStream containing .resources file data for the .resx file</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private static MemoryStream ProvideResourceDataForResx(string resourceFullFilename,
bool targetLessThan4)
{
MemoryStream shortLivedBackingStream = new MemoryStream();
using (ResourceWriter resourceWriter = new ResourceWriter(shortLivedBackingStream))
{
using (ResXResourceReader resourceReader = new ResXResourceReader(resourceFullFilename))
{
IDictionaryEnumerator dictionaryEnumerator = resourceReader.GetEnumerator();
while (dictionaryEnumerator.MoveNext())
{
string resourceKey = dictionaryEnumerator.Key as string;
if (resourceKey != null)  // Should not be possible
resourceWriter.AddResource(resourceKey, dictionaryEnumerator.Value);
}
}
}

// Get reference to the buffer used by shortLivedBackingStream, which is now closed because
//  resourceWriter was disposed. If relevant, fix version number for System.Drawing.
byte[] backingStreamBuffer = shortLivedBackingStream.GetBuffer();
if (targetLessThan4)
ChangeSystemDrawingVersionNumber(backingStreamBuffer);

// Create new MemoryStream because shortLivedBackingStream is closed
return new MemoryStream(backingStreamBuffer);
}


/// <summary>
/// Method to change the System.Drawing version number from "4.0.0.0" to "2.0.0.0" in the
/// binary data that represents a .resources file. This implementation is based on the
/// assumption that character data in the .resources file is in UTF-8 encoding.
/// </summary>
private static void ChangeSystemDrawingVersionNumber(byte[] dataBuffer)
{
byte[] byteArray1 = Encoding.UTF8.GetBytes("System.Drawing, Version=4.0.0.0");
byte[] byteArray2 = Encoding.UTF8.GetBytes("System.Drawing, Version=2.0.0.0");

for (int i = 0; i < dataBuffer.Length - byteArray1.Length; i++)
if (ArrayEquals(byteArray1, dataBuffer, i))
Array.Copy(byteArray2, 0, dataBuffer, i, byteArray2.Length);
}


/// <summary>
/// Method to test for a byte array in a larger byte array that is being searched. No error
/// checking is done - it assumed an indexing error is not possible.
/// </summary>
private static bool ArrayEquals(byte[] searchArray, byte[] searchedArray,
int searchedArrayIndex)
{
for (int i = 0; i < searchArray.Length; i++)
if (searchArray[i] != searchedArray[searchedArrayIndex + i])
return false;
return true;
}

Изменение: в предыдущей версии этого ответа я использовал метод ResourceWriter.TypeNameConverter. Это работало в некоторых ситуациях, но не в других, и там есть отчет об ошибке, который указывает, что могут быть проблемы с этим кодом, по крайней мере для соответствующего кода в.Net Core: https://github.com/dotnet/corefx/issues/11083.

Ответ №11

Вот простое решение, которое сработало для меня:

У меня была такая же ошибка. Мой код является примером в пакете EMGU FeatureMatching с использованием VS2017.

Кажется, что ошибка возникает из-за несоответствия между версией System.Drawing.dll и Target Framework.

Чтобы исправить это, я удалил System.Drawing (щелкните правой кнопкой мыши в обозревателе решений в разделе “Ссылки”). Затем я щелкнул “Добавить ссылку” (щелкните правой кнопкой мыши “Ссылки” в обозревателе решений) и перешел к следующей папке: C:WindowsMicrosoft.NETFramework

В нем находятся папки с метками v1.xxxx, v2.xxxx, v3.xxxx и т.д. Я открыл папку v4.0.30319 и выбрал в ней файл System.Drawing.dll. Нажмите Ok.

Затем я перешел к установке Target Framework. Перейдите в меню Project> YourApp Properties (внизу меню). Выберите приложение слева. Есть раскрывающийся список для “Целевой рамки”. Я выбрал .NET Framework 4 “. Я получаю сообщение о страшной потере чего-либо и о том, что проект будет закрыт и вновь открыт. Я нажал кнопку” ОК “, проект закрылся и сразу же открылся.

Я запустил свой проект, и теперь он в порядке.

Понравилась статья? Поделить с друзьями:
  • Could not find kernel image windows 7
  • Could not debug privilege are you admin windows 10
  • Could not create the java virtual machine что делать windows 10
  • Could not create ssl tls secure channel windows 7
  • Could not connect to server connection refused postgresql windows