The given key was not present in the dictionary как исправить

Windows Server 2008 R2 Enterprise Windows Server 2008 R2 Datacenter Windows Server 2008 R2 Foundation Windows Server 2008 R2 Standard Windows Server 2008 R2 Web Edition Windows 7 Enterprise Windows 7 Home Basic Windows 7 Home Premium Windows 7 Professional Windows 7 Starter Windows 7 Ultimate More…Less

Symptoms

Assume that you use Active Directory cmdlets to interrogate Active Directory objects on a computer that is running Windows Server 2008 R2 or on a Windows 7-based computer that has the Remote Server Administration Tools feature installed. When you try to run the Get-ADObject cmdlet, you receive an error message that resembles the following:

The given key was not present in the dictionary.

Cause

This issue occurs because the cmdlet query returns an attribute that is not listed in the aggregate schema. When the Windows PowerShell cmdlet formats the attributes for the result of cmdlet query, the cmdlet retrieves a list of interesting attributes from Active Directory to track the formatting operation. Then, the cmdlet compares this list against the list of attributes that are retrieved for the aggregate schema. When the cmdlet query returns an attribute that is not listed in the aggregate schema, the issue that is described in the «Symptoms» section occurs.

Resolution

Hotfix information

A supported hotfix is available from Microsoft. However, this hotfix is intended to correct only the problem that is described in this article. Apply this hotfix only to systems that are experiencing the problem described in this article. This hotfix might receive additional testing. Therefore, if you are not severely affected by this problem, we recommend that you wait for the next software update that contains this hotfix.

If the hotfix is available for download, there is a «Hotfix download available» section at the top of this Knowledge Base article. If this section does not appear, contact Microsoft Customer Service and Support to obtain the hotfix.

Note If additional issues occur or if any troubleshooting is required, you might have to create a separate service request. The usual support costs will apply to additional support questions and issues that do not qualify for this specific hotfix. For a complete list of Microsoft Customer Service and Support telephone numbers or to create a separate service request, visit the following Microsoft website:

http://support.microsoft.com/contactus/?ws=supportNote The «Hotfix download available» form displays the languages for which the hotfix is available. If you do not see your language, it is because a hotfix is not available for that language.

Prerequisites

To apply this hotfix, you must be running Windows 7 Service Pack 1 (SP1) or Windows Server 2008 R2 SP1.

For more information about how to obtain a Windows 7 or Windows Server 2008 R2 service pack, click the following article number to view the article in the Microsoft Knowledge Base:

976932Information about Service Pack 1 for Windows 7 and for Windows Server 2008 R2

Registry information

To apply this hotfix, you do not have to make any changes to the registry.

Restart requirement

You must restart the computer after you apply this hotfix.

Hotfix replacement information

This hotfix does not replace a previously released hotfix.

File information

The global version of this hotfix installs files that have the attributes that are listed in the following tables. The dates and the times for these files are listed in Coordinated Universal Time (UTC). The dates and the times for these files on your local computer are displayed in your local time together with your current daylight saving time (DST) bias. Additionally, the dates and the times may change when you perform certain operations on the files.

Windows 7 and Windows Server 2008 R2 file information notes


Important Windows 7 hotfixes and Windows Server 2008 R2 hotfixes are included in the same packages. However, hotfixes on the Hotfix Request page are listed under both operating systems. To request the hotfix package that applies to one or both operating systems, select the hotfix that is listed under «Windows 7/Windows Server 2008 R2» on the page. Always refer to the «Applies To» section in articles to determine the actual operating system that each hotfix applies to.

  • The files that apply to a specific product, SR_Level (RTM, SPn), and service branch (LDR, GDR) can be identified by examining the file version numbers as shown in the following table:

    Version

    Product

    Milestone

    Service branch

    6.1.760
    1.22xxx

    Windows 7 and Windows Server 2008 R2

    SP1

    LDR

  • The MANIFEST files (.manifest) and the MUM files (.mum) that are installed for each environment are listed separately in the «Additional file information for Windows 7 and for Windows Server 2008 R2» section. MUM and MANIFEST files, and the associated security catalog (.cat) files, are extremely important to maintaining the state of the updated component. The security catalog files, for which the attributes are not listed, are signed with a Microsoft digital signature.

For all supported x86-based versions of Windows 7

File name

File version

File size

Date

Time

Platform

Microsoft.activedirectory.management.dll

6.1.7601.22079

774,144

06-Aug-2012

17:12

x86

For all supported x64-based versions of Windows 7 and of Windows Server 2008 R2

File name

File version

File size

Date

Time

Platform

Microsoft.activedirectory.management.dll

6.1.7601.22079

774,144

06-Aug-2012

18:11

x86

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section.

More Information

For more information about software update terminology, click the following article number to view the article in the Microsoft Knowledge Base:

824684Description of the standard terminology that is used to describe Microsoft software updates

Additional file information

Additional file information for Windows 7 and for Windows Server 2008 R2

Additional files for all supported x86-based versions of Windows 7

File name

X86_a72e15df5fd0ce2c991e6e8f403daead_31bf3856ad364e35_6.1.7601.22079_none_8aa6ed2c8a8746ce.manifest

File version

Not applicable

File size

706

Date (UTC)

07-Aug-2012

Time (UTC)

09:46

Platform

Not applicable

File name

X86_microsoft.activedirectory.management_31bf3856ad364e35_6.1.7601.22079_none_1aeb5954edaf626a.manifest

File version

Not applicable

File size

2,809

Date (UTC)

06-Aug-2012

Time (UTC)

17:33

Platform

Not applicable

Additional files for all supported x64-based versions of Windows 7 and of Windows Server 2008 R2

File name

Amd64_6d4f87cd9f3324175b411631038a43a5_31bf3856ad364e35_6.1.7601.22079_none_215c5e0ff5ba5791.manifest

File version

Not applicable

File size

710

Date (UTC)

07-Aug-2012

Time (UTC)

09:46

Platform

Not applicable

File name

Amd64_a72e15df5fd0ce2c991e6e8f403daead_31bf3856ad364e35_6.1.7601.22079_none_e6c588b042e4b804.manifest

File version

Not applicable

File size

708

Date (UTC)

07-Aug-2012

Time (UTC)

09:46

Platform

Not applicable

File name

Amd64_microsoft.activedirectory.management_31bf3856ad364e35_6.1.7601.22079_none_7709f4d8a60cd3a0.manifest

File version

Not applicable

File size

2,813

Date (UTC)

06-Aug-2012

Time (UTC)

18:46

Platform

Not applicable

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Is there a way to get the value of the given key in the following exception in C# in a way that affects all generic classes? I think this is a big miss in the exception description from Microsoft.

The given key was not present in the dictionary.

A better way would be:

The given key ‘» + key.ToString() + «‘ was not present in the dictionary.

Solutions might involve mixins or derived classes maybe.

Dale K's user avatar

Dale K

24.7k15 gold badges42 silver badges71 bronze badges

asked Oct 7, 2014 at 20:06

Andreas's user avatar

13

This exception is thrown when you try to index to something that isn’t there, for example:

Dictionary<String, String> test = new Dictionary<String,String>();
test.Add("Key1","Value1");
string error = test["Key2"];

Often times, something like an object will be the key, which undoubtedly makes it harder to get. However, you can always write the following (or even wrap it up in an extension method):

if (test.ContainsKey(myKey))
   return test[myKey];
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Or more efficient (thanks to @ScottChamberlain)

T retValue;
if (test.TryGetValue(myKey, out retValue))
    return retValue;
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Microsoft chose not to do this, probably because it would be useless when used on most objects. Its simple enough to do yourself, so just roll your own!

YounesM's user avatar

YounesM

2,26915 silver badges28 bronze badges

answered Oct 7, 2014 at 20:10

BradleyDotNET's user avatar

BradleyDotNETBradleyDotNET

60.1k10 gold badges95 silver badges116 bronze badges

4

In the general case, the answer is No.

However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.

In Visual Studio, this option is located here:

Debug → Exceptions… → Common Language Runtime Exceptions → System.Collections.Generic

There, you can check the Thrown box.


For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue> and not tied directly to Dictionary<TKey, TValue>, you can implement your own dictionary class which provides this behavior.

answered Oct 7, 2014 at 20:09

Sam Harwell's user avatar

Sam HarwellSam Harwell

97.3k20 gold badges207 silver badges279 bronze badges

4

If you want to manage key misses you should use TryGetValue

https://msdn.microsoft.com/en-gb/library/bb347013(v=vs.110).aspx

string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = "tif", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = "tif" is not found.");
}

Kolappan N's user avatar

Kolappan N

3,5212 gold badges33 silver badges42 bronze badges

answered Oct 7, 2014 at 20:09

gabba's user avatar

gabbagabba

2,8052 gold badges26 silver badges47 bronze badges

1

If anyone still cares in 2021 and can afford to move to .NET Core, .Net 5 finally tells us the name of the offending key:

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, object> dictionary = new()
        {
            ["foo"] = new object()
        };
        Console.WriteLine(dictionary["bar"]);
    }
}

Will give you:

Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'bar' was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at KnfTest.Program.Main(String[] args)

The same code in .Net Framework 4.8 gives the old dreaded message.

As for those who can’t afford moving to Core yet I’m afraid there is no real working solution. Replacing all indexer invocations with TryGetValue is cumbersome -not to say absurd. Subclassing from Dictionary is practically impossible. Yes you can declare a new indexer but then polymorphism goes out the window as your indexer will be called only when using a reference of the subclass. Finally, creating your own Dictionary wrapper might be a solution but that’s again a non trivial process, especially if you want to replicate exactly the Dictionary which implements not only IDictionary<TKey,TValue> but also:

System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>
System.Collections.IDictionary
System.Runtime.Serialization.IDeserializationCallback
System.Runtime.Serialization.ISerializable

Quite an overkill «just» for an exception message.

answered Nov 23, 2021 at 17:06

Stelios Adamantidis's user avatar

1

string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"

With this code, we will get string data in ‘Value’. If key ‘Name’ exists in the dictionary ‘dic’ then fetch this value, else returns «Required Name» string.

answered Feb 8, 2019 at 9:13

Sharon AS's user avatar

Sharon ASSharon AS

3643 silver badges6 bronze badges

1

You can try this code

Dictionary<string,string> AllFields = new Dictionary<string,string>();  
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);

If the key is not present, it simply returns a null value.

answered Apr 8, 2019 at 11:01

Nitika Chopra's user avatar

Borrowed from @BradleyDotNET’s anwser, here’s the extension method version:

public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key) 
{
    if (dictionary.TryGetValue(key, out TValue result)) 
    {
        return result;
    } 
    else 
    {
        throw new KeyNotFoundException($"The given key '{key}' was not present in the dictionary.");
    }
}

answered Sep 10, 2021 at 12:02

Rohim Chou's user avatar

Rohim ChouRohim Chou

7979 silver badges16 bronze badges

In C# 7.0 or greater, you can Use the out parameter modifer to solve your problem in one line, and only make one call to the indexer. It works in c# 7.0 or greater.

public TItem GetOrException<TKey,TItem>(TKey key) where TKey : IFormattable => 
    dictionary.TryGetValue(key, out var item) ? item : throw new KeyNotFoundException( "Key: " + key.ToString() );

You can also opt for the longer try catch block which gives better exception information:

public TItem GetOrException<TKey,TItem>(TKey key) where TKey : IFormattable {
    try{ return dictionary[key]; }
    catch (KeyNotFoundException e) { throw new KeyNotFoundException("Key:" + key.ToString(), e);}
}

answered Jan 12, 2022 at 20:21

Greg's user avatar

GregGreg

1,5191 gold badge20 silver badges33 bronze badges

In this guide, we’ll walk you through the steps to troubleshoot and fix the common error message «The given key was not present in the dictionary» that occurs in various programming languages and platforms.

Table of Contents

  1. Introduction
  2. Understanding the Error
  3. Common Causes of the Error
  4. Step-by-Step Solutions
  5. FAQs

Introduction

«The given key was not present in the dictionary» is an error message that occurs when a program tries to access a key in a dictionary (or a similar data structure) that doesn’t exist. This error is common in languages like Python, C#, and JavaScript, where dictionaries, hashmaps, or objects are commonly used for storing data.

Understanding the Error

A dictionary (or a hashmap) is a data structure that stores key-value pairs. The keys in a dictionary are unique, and each key is associated with a specific value. When a program tries to access a value using a key that doesn’t exist in the dictionary, it raises an error. This error is often referred to as «The given key was not present in the dictionary» error.

Common Causes of the Error

  1. Typographical errors: A simple typo in the key name can cause this error. Make sure you’re using the correct key name and case sensitivity when accessing the dictionary.
  2. Missing data: The key might not be present in the dictionary because the data is missing or hasn’t been added yet. Ensure that the data is being added to the dictionary correctly.
  3. Concurrency issues: In multi-threaded applications, the dictionary might be modified by another thread while you’re trying to access it. Consider using thread-safe dictionaries or proper synchronization mechanisms to avoid this issue.

Step-by-Step Solutions

Here are some step-by-step solutions to fix the «The given key was not present in the dictionary» error:

Solution 1: Check for Typographical Errors

  1. Identify the line of code where the error occurs.
  2. Verify that the key being used to access the dictionary is spelled and capitalized correctly.
  3. Check the dictionary definition to ensure the key is present.

Solution 2: Ensure Data is Being Added to the Dictionary

  1. Identify the part of your code where data is being added to the dictionary.
  2. Verify that the missing key is being added correctly.
  3. If the data is being read from an external source, ensure that the data is complete and correctly formatted.

Solution 3: Use Proper Synchronization Mechanisms

  1. If you’re working with a multi-threaded application, identify the parts of your code where the dictionary is being accessed or modified.
  2. Use thread-safe dictionaries or implement proper synchronization mechanisms to avoid concurrency issues.

FAQs

1. Can I avoid the error by using a default value when the key is not present?

Yes, many programming languages provide ways to access dictionary values with a default value when the key is not present. For example, in Python, you can use the get() method:

value = my_dictionary.get('missing_key', 'default_value')

2. How can I check if a key exists in a dictionary before accessing it?

You can use the in operator in Python or the ContainsKey() method in C# to check if a key exists in a dictionary:

if 'key' in my_dictionary:
    value = my_dictionary['key']
if (myDictionary.ContainsKey("key"))
{
    value = myDictionary["key"];
}

3. Can I catch the error and handle it programmatically?

Yes, you can use exception handling mechanisms like try and catch in C# or try and except in Python to catch the error and handle it:

try:
    value = my_dictionary['missing_key']
except KeyError:
    value = 'default_value'
try
{
    value = myDictionary["missingKey"];
}
catch (KeyNotFoundException)
{
    value = "defaultValue";
}

4. How can I list all the keys or values in a dictionary?

You can use the keys() and values() methods in Python or the Keys and Values properties in C#:

keys = my_dictionary.keys()
values = my_dictionary.values()
var keys = myDictionary.Keys;
var values = myDictionary.Values;

5. How can I merge two dictionaries?

Most programming languages provide ways to merge dictionaries. In Python, you can use the update() method or dictionary unpacking:

merged_dictionary = {**dict1, **dict2}

In C#, you can use the Union() method from LINQ:

var mergedDictionary = dict1.Union(dict2).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

For more information and examples on dictionaries, refer to the following guides:

  1. Python Dictionary
  2. C# Dictionary
  3. JavaScript Object

This C# exception article demonstrates the KeyNotFoundException.

KeyNotFoundException. A KeyNotFoundException was thrown.

This is likely caused by an invalid usage of the Dictionary collection. As always we want a quick way to fix the problem. We look at correct and incorrect examples.

Example. First, here we see some code that looks correct. But it has a severe flaw. This is the problem: you cannot look up a key that is not found in the Dictionary and try to assign your variable to its value.

Here: The KeyNotFoundException is thrown on the final line of try-block. The string «test» is not present in the collection.

TryCatch

C# program that throws KeyNotFoundException

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	try
	{
	    //
	    // Create new Dictionary with string key of "one"
	    //
	    Dictionary<string, string> test = new Dictionary<string, string>();
	    test.Add("one", "value");

	    //
	    // Try to access key of "two"
	    //
	    string value = test["two"];
	}
	catch (Exception ex)
	{
	    //
	    // An exception will be thrown.
	    //
	    Console.WriteLine(ex);
	}
    }
}

Output

System.Collections.Generic.KeyNotFoundException:
    The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()
...

Example 2. We can fix this exception by using the TryGetValue method on the Dictionary constructed type. Note that could use ContainsKey instead of TryGetValue, but the below code preserves the intention of the previous code.

ContainsKeyTryGetValue

C# program that does not throw

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	Dictionary<string, string> test = new Dictionary<string, string>();
	test.Add("one", "value");
	//
	// Use TryGetValue to avoid KeyNotFoundException.
	//
	string value;
	if (test.TryGetValue("two", out value))
	{
	    Console.WriteLine("Found");
	}
	else
	{
	    Console.WriteLine("Not found");
	}
    }
}

Output

Not found

You always have to use the if-statement when testing values in the Dictionary, because there is always a possibility that the key will not exist. The C# compiler cannot detect missing keys. They can only be detected at runtime.

Tester-DoerCompile-Time Error

Summary. We saw how to raise and catch the KeyNotFoundException during runtime. We then saw how to avoid causing the exception. We discussed alternatives, such as TryGetValue and ContainsKey, and looked at a program that does not have this problem.


Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

An System.Collections.Generic.KeyNotFoundException “The given key was not present in the dictionary” can be the result of using a too old MySQL Connector/NET version in your ASP.NET web application. A KeyNotFoundException is thrown when an operation attempts to retrieve an element from a collection using a key that does not exist in that collection. An unsupported character set like utf8mb4 can be such a key, if your Connector/NET doesn’t support this character set. Luckily there is an easy workaround for this.

MySQL (Oracle) Connector/NET versions prior to 6.0.8, 6.1.6, 6.2.5, 6.3.6 lack a mapping for UTF8MB4 as charset. Connecting to a MySQL database and querying a table that has been created with CHARSET=utf8mb4 results in a .NET exception:

Exception Details: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at MySql.Data.MySqlClient.CharSetMap.GetCharacterSet(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.CharSetMap.GetEncoding(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.Driver.Configure(MySqlConnection connection) at MySql.Data.MySqlClient.MySqlConnection.Open() at ASP.mysql_data_aspx.MySQLConn()

A more extended exception is:

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at MySql.Data.MySqlClient.CharSetMap.GetCharacterSet(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.MySqlField.SetFieldEncoding() at MySql.Data.MySqlClient.NativeDriver.GetColumnData(MySqlField field) at MySql.Data.MySqlClient.NativeDriver.GetColumnsData(MySqlField[] columns) at MySql.Data.MySqlClient.Driver.GetColumns(Int32 count) at MySql.Data.MySqlClient.ResultSet.LoadColumns(Int32 numCols) at MySql.Data.MySqlClient.ResultSet..ctor(Driver d, Int32 statementId, Int32 numCols) at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId) at MySql.Data.MySqlClient.MySqlDataReader.NextResult() at MySql.Data.MySqlClient.MySqlDataReader.Close() at MySql.Data.MySqlClient.MySqlCommand.ResetReader() at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader() at ASP.mysql_data_aspx.MySQLConn()

Googling for a fix, some suggestions were to add CharSet=utf8; to your connection string. Unfortunately I was unable to resolve the exception with this added.

The best way to fix this System.Collections.Generic.KeyNotFoundException with Connector/NET is to simply update your Connector/NET version. Support for utf8mb4 charset is built in in versions 6.0.8, 6.1.6, 6.2.5, 6.3.6+:

MySQL Connector/NET did not support the utf8mb4 character set. When attempting to connect to utf8mb4 tables or columns, an exception KeyNotFoundException was generated. (Bug #58244)

https://dev.mysql.com/doc/relnotes/connector-net/en/news-6-0-8.html

And MySQL Connector/NET now supports MySQL servers configured to use utf8mb4 as the default character set in version 8.0.9.

MySQL Connector/NET now supports MySQL servers configured to use utf8mb4 as the default character set.

https://dev.mysql.com/doc/relnotes/connector-net/en/news-8-0-9.html

If, for some reason, you cannot or will not update your MySQL Connector/NET version anytime soon, there is an easy workaround available; SET NAMES 'utf8'. Yes, that’s right: as your first statement, set the three session system variables

  • character_set_client
  • character_set_connection
  • character_set_results

to the given character set utf8. You can even use latin1, but that may give some undesired encoding issues…

Imaging the following C# MySql.Data.MySqlClient test script for querying your MySQL database table:

string sql = "select * from aspnet_site_comments";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read()) {
	Response.Write(rdr[0]+ "<br/>");
}
rdr.Close();
}

catch (Exception ex) {
	Response.Write(ex.ToString());
}Code language: C# (cs)

Are you looking for rock solid, eco-friendly, .NET hosting? Look no further! UmbHost offers powerful hosting services for websites and businesses of all sizes, and is powered by 100% renewable energy!

If your MySQL database server has in its my.cnf server config:

character_set_server utf8mb4
collation_server = utf8mb4_unicode_ciCode language: SQL (Structured Query Language) (sql)

And your table aspnet_site_comments is created using ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci, it throws an System.Collections.Generic.KeyNotFoundException exception. Alter your code to first set the character_set_* to utf8 (don’t mind my pseudo-code, you’ll get the idea) as a workaround for this issue:

string setcharset = "SET NAMES 'utf8'";	// <-- !!
MySqlCommand charsetcmd = new MySqlCommand(setcharset, conn);
MySqlDataReader charsetrdr = charsetcmd.ExecuteReader();
charsetrdr.Close()

string sql = "select * from aspnet_site_comments";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read()) {
	Response.Write(rdr[0]+ "<br/>");
}
rdr.Close();
}

catch (Exception ex) {
	Response.Write(ex.ToString());
}Code language: C# (cs)

Only use this as a temporary fix, you should still update Connector/NET ASAP. That’s it!

Protip: Donate $10, 20 or 30 through Paypal (or see my donate page) and support this site. Thank you <3

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как составить прогноз производства продукции
  • Как найти подводный данж в майнкрафт командой
  • Как найти дисперсию непрерывной случайной величины
  • Как вконтакте найти то что я лайкала
  • Как найти количество процентов от суммы

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии