Меню

С read any лун

Console. Read Key Метод

Определение

Получает следующий нажатый пользователем символ или функциональную клавишу. Obtains the next character or function key pressed by the user.

Перегрузки

Получает следующий нажатый пользователем символ или функциональную клавишу. Obtains the next character or function key pressed by the user. Нажатая клавиша отображается в окне консоли. The pressed key is displayed in the console window.

Получает следующий нажатый пользователем символ или функциональную клавишу. Obtains the next character or function key pressed by the user. Нажатая клавиша может быть отображена в окне консоли. The pressed key is optionally displayed in the console window.

ReadKey()

Получает следующий нажатый пользователем символ или функциональную клавишу. Obtains the next character or function key pressed by the user. Нажатая клавиша отображается в окне консоли. The pressed key is displayed in the console window.

Возвращаемое значение

Объект, описывающий константу ConsoleKey и символ Юникода (при наличии), соответствующий нажатой клавише консоли. An object that describes the ConsoleKey constant and Unicode character, if any, that correspond to the pressed console key. Этот объект ConsoleKeyInfo также описывает в битовой комбинации значений ConsoleModifiers, нажимались ли клавиши-модификаторы (одна или несколько) Shift, Alt или Ctrl одновременно с клавишей консоли. The ConsoleKeyInfo object also describes, in a bitwise combination of ConsoleModifiers values, whether one or more Shift, Alt, or Ctrl modifier keys was pressed simultaneously with the console key.

Исключения

Свойство In перенаправлено из потока, отличного от консоли. The In property is redirected from some stream other than the console.

Примеры

Одним из наиболее распространенных ReadKey() способов использования метода является остановка выполнения программы до тех пор, пока пользователь не нажмет клавишу и приложение не завершит работу или не отобразит дополнительное окно информации. One of the most common uses of the ReadKey() method is to halt program execution until the user presses a key and the app either terminates or displays an additional window of information. В следующем примере метод используется ReadKey() для ожидания нажатия пользователем клавиши ВВОД перед завершением работы приложения. The following example uses the ReadKey() method to wait for the user to press the Enter key before terminating the app.

Обратите внимание, что эта перегрузка ReadKey метода по умолчанию отображает все отображаемые клавиши, которые пользователь нажимает на консоль. Note that this overload of the ReadKey method by default echoes any displayable keys that the user presses to the console. Чтобы подавить их, вызовите ReadKey метод с intercept аргументом true . To suppress them, call the ReadKey method with an intercept argument of true .

В следующем примере метод используется ReadKey() для вывода сведений о том, какой ключ пользователь нажал. The following example uses the ReadKey() method to display information about which key the user pressed.

Комментарии

ReadKeyМетод ожидает, то есть блокирует поток, выдающий ReadKey метод, пока не будет нажата клавиша со знаком или функцией. The ReadKey method waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed. Символ или клавиша может быть нажата в сочетании с одним или несколькими клавишами-модификаторами Alt, CTRL или Shift. A character or function key can be pressed in combination with one or more Alt, Ctrl, or Shift modifier keys. Однако нажатие клавиши-модификатора сама по себе не приведет к ReadKey возврату метода. However, pressing a modifier key by itself will not cause the ReadKey method to return.

В зависимости от приложения может потребоваться использовать ReadKey метод в сочетании со KeyAvailable свойством. Depending on your application, you might want to use the ReadKey method in conjunction with the KeyAvailable property.

ReadKeyМетод считывает данные с клавиатуры, даже если стандартные входные данные перенаправляются в файл с SetIn методом. The ReadKey method reads from the keyboard even if the standard input is redirected to a file with the SetIn method.

Читайте также:  Илон маск колонизация луны

См. также раздел

Применяется к

ReadKey(Boolean)

Получает следующий нажатый пользователем символ или функциональную клавишу. Obtains the next character or function key pressed by the user. Нажатая клавиша может быть отображена в окне консоли. The pressed key is optionally displayed in the console window.

Параметры

Определяет, следует ли отображать нажатую клавишу в окне консоли. Determines whether to display the pressed key in the console window. Значение true , чтобы не отображать нажатую клавишу; в противном случае — значение false . true to not display the pressed key; otherwise, false .

Возвращаемое значение

Объект, описывающий константу ConsoleKey и символ Юникода (при наличии), соответствующий нажатой клавише консоли. An object that describes the ConsoleKey constant and Unicode character, if any, that correspond to the pressed console key. Этот объект ConsoleKeyInfo также описывает в битовой комбинации значений ConsoleModifiers, нажимались ли клавиши-модификаторы (одна или несколько) Shift, Alt или Ctrl одновременно с клавишей консоли. The ConsoleKeyInfo object also describes, in a bitwise combination of ConsoleModifiers values, whether one or more Shift, Alt, or Ctrl modifier keys was pressed simultaneously with the console key.

Исключения

Свойство In перенаправлено из потока, отличного от консоли. The In property is redirected from some stream other than the console.

Примеры

Одним из наиболее распространенных ReadKey способов использования метода является остановка выполнения программы до тех пор, пока пользователь не нажмет клавишу и приложение не завершит работу или не отобразит дополнительное окно информации. One of the most common uses of the ReadKey method is to halt program execution until the user presses a key and the app either terminates or displays an additional window of information. В следующем примере метод используется ReadKey(Boolean) для ожидания нажатия пользователем клавиши ВВОД перед завершением работы приложения. The following example uses the ReadKey(Boolean) method to wait for the user to press the Enter key before terminating the app. Обратите внимание, что если пользователь нажмет какой-либо другой ключ, он не будет отображаться на консоли. Note that, if the user presses any other key, it is not echoed to the console.

В следующем примере метод используется ReadKey(Boolean) для отображения сведений о нажатой пользователем клавише без вывода этого ключа на консоль. The following example uses the ReadKey(Boolean) method to display information about the key pressed by a user without echoing that key to the console.

Комментарии

ReadKeyМетод ожидает, то есть блокирует поток, выдающий ReadKey метод, пока не будет нажата клавиша со знаком или функцией. The ReadKey method waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed. Символ или клавиша может быть нажата в сочетании с одним или несколькими клавишами-модификаторами Alt, CTRL или Shift. A character or function key can be pressed in combination with one or more Alt, Ctrl, or Shift modifier keys. Однако нажатие клавиши-модификатора сама по себе не приведет к ReadKey возврату метода. However, pressing a modifier key by itself will not cause the ReadKey method to return.

Если intercept параметр имеет значение true , нажатая клавиша перехватывается и не отображается в окне консоли; в противном случае нажатая клавиша отображается. If the intercept parameter is true , the pressed key is intercepted and not displayed in the console window; otherwise, the pressed key is displayed.

В зависимости от приложения может потребоваться использовать ReadKey метод в сочетании со KeyAvailable свойством. Depending on your application, you might want to use the ReadKey method in conjunction with the KeyAvailable property.

ReadKeyМетод считывает данные с клавиатуры, даже если стандартные входные данные перенаправляются в файл с SetIn методом. The ReadKey method reads from the keyboard even if the standard input is redirected to a file with the SetIn method.

Читайте также:  Схд луны что это

Источник

С read any лун

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

these code is only for read enter\any key, but i’m doing wrong:(

can anyone advice me?

Answers

«and i want something portable»

Your ReadConsole isn’t portable to begin with. In general, what you ask is non portable, implementation defined etc.

«, but sometimes can be ignored(depending on keyboard buffer)»

If you don’t want to show other character you could disable console echoing with SetConsoleMode:

Note that all this makes sense only if you’re dealing with actual user input. If your program’s user input has been redirected then this won’t work properly. ReadConsole & co. works only with the actual console and because of that I used CreateFile(«CONIN$». ) rather than GetStdHandle.

Note that if you do use GetStdHandle like you did in other post you have to be prepared for errors. All that code will simply not work if the input was redirected.

And do not close the handle returned by GetStdHandle, you haven’t created it in the first place.

Well, if you don’t want to open it every time you can store it in a static variable:

And drop the CloseHandle line in this case, the handle will remain open until the process ends.

All replies

How about using STD_INPUT_HANDLE instead?

i’m new with these function and that const lol

heres the code updated:

works fine, but i need, if possible anotherthing: can all keys be ignored(except enter of course)?

— you call Read();
— you press any key(inclued letters;

— but i don’t want show them;

— press enter to continue or exit something.

«and i want something portable»

Your ReadConsole isn’t portable to begin with. In general, what you ask is non portable, implementation defined etc.

«, but sometimes can be ignored(depending on keyboard buffer)»

If you don’t want to show other character you could disable console echoing with SetConsoleMode:

Note that all this makes sense only if you’re dealing with actual user input. If your program’s user input has been redirected then this won’t work properly. ReadConsole & co. works only with the actual console and because of that I used CreateFile(«CONIN$». ) rather than GetStdHandle.

Your ReadConsole isn’t portable to begin with. In general, what you ask is non portable, implementation defined etc.

«, but sometimes can be ignored(depending on keyboard buffer)»

If you don’t want to show other character you could disable console echoing with SetConsoleMode:

Note that all this makes sense only if you’re dealing with actual user input. If your program’s user input has been redirected then this won’t work properly. ReadConsole & co. works only with the actual console and because of that I used CreateFile(«CONIN$». ) rather than GetStdHandle.

you have righ. the declaration can not be portable:(

Источник

How To Read .Key file on C#?

I read the .der file as follows.

but it doesn’t have private key. It has only public key.

cert.HasPrivateKey return false.

When I search it, I found that ‘.der file doesn’t have private Key, private Key is in .key file’.

I use Notepad ++ to open a .key file in the same path as the .der file, the broken text will be printed.

first question, How to read private key from .key file on C#?

and second, How to convert .key file to .pem file on C#? Is it just using openssl?

I would appreciate your teaching.

2 Answers 2

Current versions of .NET don’t have a very good story here. .NET Core 3.0 has a better story. And if you’re willing to use NuGet packages with «Experimental» in their name there’s a differently better story.

Читайте также:  Театр луны что посмотреть

Note: Throughout this answer I’m not going to consider third party libraries like BouncyCastle. It might do what you want perfectly, but it’s not my area of expertise. I will consider NuGet packages developed by the same set of people as work on the inbox libraries for .NET, when I know of them.

Interpretation 1: «What single method do I call to load a private key from a file?»

Current versions

.NET Core 3.0

There’s not a single answer, you need to know what kind of file you have (or just try al the answers).

  • RSA
    • ImportRSAPrivateKey
      • For when the data is in the PKCS#1 RSAPrivateKey format (PEM open header: BEGIN RSA PRIVATE KEY)
    • ImportPkcs8PrivateKey
      • For when the data is in the PKCS#8 PrivateKeyInfo format (PEM open header: BEGIN PRIVATE KEY)
    • ImportEncryptedPkcs8PrivateKey
      • For when the data is in the PKCS#8 EncryptedPrivateKeyInfo format (PEM open header: BEGIN ENCRYPTED PRIVATE KEY)
  • ECDSA
    • ImportECPrivateKey
      • For when the data is in the RFC 5915 ECPrivateKey format (PEM open header: BEGIN EC PRIVATE KEY)
    • ImportPkcs8PrivateKey
    • ImportEncryptedPkcs8PrivateKey
  • ECDiffieHellman
    • ImportECPrivateKey
    • ImportPkcs8PrivateKey
    • ImportEncryptedPkcs8PrivateKey
  • DSA
    • ImportPkcs8PrivateKey
    • ImportEncryptedPkcs8PrivateKey

The caveat to these methods is that they only understand BER/DER data, not PEM data. So if your file is in the PEM format (which makes it easiest to identify what the payload is supposed to be) you first need to convert it to BER/DER.

For most PEM files that’s easy: you just find the contents between the BEGIN and END markers, run it through Convert.FromBase64String, and voila. Technically PEM supports attributes, and dealing with those is harder (and beyond the scope of this answer).

So, you might end up with something like

The ignored out values are the number of bytes that were used from the input bytes. It’s mainly only relevant when reading from the middle of a file.

System.Security.Cryptography.Asn1.Experimental

No solution, this library is much lower level than that.

Interpretation 2: «How do I understand these files in practice?»

Okay, this isn’t really a way the question was interpreted, but a segue.

Cryptographic key files are always (in my experience) DER- (though occasionally relaxed to BER-) encoded ASN.1 data structures. To fully understand them you would need to read and understand

  • ITU-T REC X.680: The ASN.1 language
  • ITU-T REC X.690 The Basic Encoding Rules (BER) byte layout for ASN.1 data (and also the rarely-used restrictions Canonical Encoding Rules (CER) and commonly-used restrictions Distinguished Encoding Rules (DER)).
  • Whatever thing describes the particular formats, and possibly things they reference.
    • RSAPrivateKey: Public Key Cryptography Standards #1 (PKCS#1) or RFC 8017
    • ECPrivateKey: RFC 5915
    • PKCS#8 PrivateKeyInfo: PKCS#8 / RFC 5208
    • PKCS#8 EncryptedPrivateKeyInfo: PKCS#8 / RFC 5208 (and PKCS#5, at least, as dependencies)

These structures are then sometimes converted to a textual representation using the Privacy Enhanced Mail (PEM) syntax, which is essentially

  • 5 hyphen-minus characters
  • All-caps BEGIN followed by a space
  • A format identifier, not ending in a space
  • 5 hyphen-minus characters
  • A newline (CRLF or LF)
  • The base64-encoded version of the BER/DER data, wrapped at 64 characters per line
  • A newline (CRLF or LF) at the end of the last part of the base64 data
  • 5 hyphen-minus characters
  • All-caps END followed by a space
  • The same format identifier used in BEGIN
  • 5 hyphen-minus characters
  • (ideally a newline or just end-of-file)

See RFC 7468 for more information.

Interpretation 3: «How do I read the parts of these files in code?»

Current versions

.NET Core 3.0

System.Security.Cryptography.Asn1.Experimental

This NuGet package is the ASN.1 reader from .NET Core 2.1 / 3.0 made public (with the idea that it becomes public from .NET Core after some usability feedback).

Источник

Adblock
detector