Read from location on console C#

c# console read int
how to read multiple values from console in c#
console.read c#
c# read from console until enter
c# console read string
c# read file
console read char c#
c# string to int

I need to read text from a particular location in the console, say 5,5.

If I were to need to write to this location, it would simply be:

Console.SetCursorPosition(5, 5);
Console.Write("My text");

Is there any way i can read in a similar way?

Just to clarify: I don't want to stop to take an input from the user, there's a chance even that the input won't be from the user, but something previously printed out. I literally want some sort of: Console.GetCharAtLocation(5,5) or something similar.

This functionality doesn't exist. It's theoretically possible for you to override the input and output streams on the console to keep your own copy of the console buffer that you could read from, but it would be non-trivial (and probably couldn't support all of the edge cases such as an external program hooking into your console and reading/writing to it).

Console.Read Method (System), Use the ReadLine() method to read input from the console in C#. This method receives the input as string, therefore you need to convert it. Here is a C# code utility that can read what's currently in the Console buffer (not the window, the buffer): Sample usage: class Program { static void Main(string[] args) { // read 10 lines from the top of the console buffer foreach (string line in ConsoleReader.ReadFromBuffer(0, 0, (short)Console.BufferWidth, 10)) { Console.Write(line); } } }

Here is a C# code utility that can read what's currently in the Console buffer (not the window, the buffer):

Sample usage:

class Program
{
    static void Main(string[] args)
    {
        // read 10 lines from the top of the console buffer
        foreach (string line in ConsoleReader.ReadFromBuffer(0, 0, (short)Console.BufferWidth, 10))
        {
            Console.Write(line);
        }
    }
}

Utility:

public class ConsoleReader
{
    public static IEnumerable<string> ReadFromBuffer(short x, short y, short width, short height)
    {
        IntPtr buffer = Marshal.AllocHGlobal(width * height * Marshal.SizeOf(typeof(CHAR_INFO)));
        if (buffer == null)
            throw new OutOfMemoryException();

        try
        {
            COORD coord = new COORD();
            SMALL_RECT rc = new SMALL_RECT();
            rc.Left = x;
            rc.Top = y;
            rc.Right = (short)(x + width - 1);
            rc.Bottom = (short)(y + height - 1);

            COORD size = new COORD();
            size.X = width;
            size.Y = height;

            const int STD_OUTPUT_HANDLE = -11;
            if (!ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE), buffer, size, coord, ref rc))
            {
                // 'Not enough storage is available to process this command' may be raised for buffer size > 64K (see ReadConsoleOutput doc.)
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            IntPtr ptr = buffer;
            for (int h = 0; h < height; h++)
            {
                StringBuilder sb = new StringBuilder();
                for (int w = 0; w < width; w++)
                {
                    CHAR_INFO ci = (CHAR_INFO)Marshal.PtrToStructure(ptr, typeof(CHAR_INFO));
                    char[] chars = Console.OutputEncoding.GetChars(ci.charData);
                    sb.Append(chars[0]);
                    ptr += Marshal.SizeOf(typeof(CHAR_INFO));
                }
                yield return sb.ToString();
            }
        }
        finally
        {
            Marshal.FreeHGlobal(buffer);
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct CHAR_INFO
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public byte[] charData;
        public short attributes;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct COORD
    {
        public short X;
        public short Y;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct SMALL_RECT
    {
        public short Left;
        public short Top;
        public short Right;
        public short Bottom;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct CONSOLE_SCREEN_BUFFER_INFO
    {
        public COORD dwSize;
        public COORD dwCursorPosition;
        public short wAttributes;
        public SMALL_RECT srWindow;
        public COORD dwMaximumWindowSize;
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool ReadConsoleOutput(IntPtr hConsoleOutput, IntPtr lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, ref SMALL_RECT lpReadRegion);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr GetStdHandle(int nStdHandle);
}

Way to read input from console in C#, As soon as the user press ENTER key it terminates. Syntax: public static int Read ();. Return Value: It returns the next character from the input stream, or a negative​  C# Console.ReadLine() Example. In this example, we will write a .NET Core console application that gathers information from an end user and then we will process that data and print some results to the screen. Start by creating a new Project (File > New > Project…) and select the .NET Core Console App template.

A simplified demo that works in Windows 10 for reading a single character from the specified (X, Y) position on the screen. Tested with .NET 4.7.2

First, here's a line of code which populates the Console with a demo grid. Note that it should render in the top left corner of your screen in order for the demo to work.

        static void Populate_Console()
        {
            Console.Clear();
            Console.Write(@"
 ┌───────┐
1│C D E F│
2│G H I J│
3│K L M N│
4│O P Q R│
 └───────┘
  2 4 6 8

    ".TrimStart('\r', '\n'));
        }

It should look like this:

Now let's read some characters back. To start you'll need the native console handle for stdout. Here's the P/Invoke method for getting it from Win32:

[DllImport("kernel32", SetLastError = true)]
static extern IntPtr GetStdHandle(int num);

Now for the cool part; this seems to be the only answer on this page so far which uses the ReadConsoleOutputCharacter Win32 function. Although it doesn't let you get the character color attributes, this approach does save all the trouble of dealing with copy rectangles and having to use CreateConsoleScreenBuffer to allocate screen buffers and copy between them.

There are separate Ansi and Unicode versions, and you need to call the proper one depending on the code page that's active in the Console window. I show both P/Invoke signatures here, but for simplicity, in the example I'll just continue with the Ansi version:

    [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
    [return: MarshalAs(UnmanagedType.Bool)] //   ̲┌──────────────────^
    static extern bool ReadConsoleOutputCharacterA(
        IntPtr hStdout,   // result of 'GetStdHandle(-11)'
        out byte ch,      // A̲N̲S̲I̲ character result
        uint c_in,        // (set to '1')
        uint coord_XY,    // screen location to read, X:loword, Y:hiword
        out uint c_out);  // (unwanted, discard)

    [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)] //   ̲┌───────────────────^
    static extern bool ReadConsoleOutputCharacterW(
        IntPtr hStdout,   // result of 'GetStdHandle(-11)'
        out Char ch,      // U̲n̲i̲c̲o̲d̲e̲ character result
        uint c_in,        // (set to '1')
        uint coord_XY,    // screen location to read, X:loword, Y:hiword
        out uint c_out);  // (unwanted, discard)

You may notice I've stripped down the marshaling on these to the bare minimum needed for the purposes of my example code, which is designed to only fetch one character at a time. Therefore, you will probably find that c_in must always be 1, due to the managed pointer declarations ‘out byte ch’ and ‘out Char ch’.

That's really all you need; calling the appropriate P/Invoke function as described above is mostly self-explanatory if you limit yourself to reading a single character. To show this with a trivial example, I'll finish with the cute demo program, that reads four characters back from the Console, along a diagonal of the grid we drew above.

static void Windows_Console_Readback()
{
    var stdout = GetStdHandle(-11);

    for (uint coord, y = 1; y <= 4; y++)
    {
        coord = (5 - y) * 2;        // loword  <-- X coord to read
        coord |= y << 16;           // hiword  <-- Y coord to read

        if (!ReadConsoleOutputCharacterA(
                stdout,
                out byte chAnsi,    // result: single ANSI char
                1,                  // # of chars to read
                coord,              // (X,Y) screen location to read (see above)
                out _))             // result: actual # of chars (unwanted)
            throw new Win32Exception();

        Console.Write(" " + (Char)chAnsi + " ");
    }
}

And there you have it...


Notes:1. The code may use some C# compiler features from 7.2. For Visual Studion 2017, enable the "latest" option in your 'Project Properties' advanced build options.

Console.Read() Method in C#, Console.ReadLine() Method in C#. This method is used to read the next line of And if standard input is redirected to a file, then this method reads a line of text  Click Visual C# Projects under Project Types, and then click Console Application under Templates Note In Visual Studio 2005 or Visual Studio 2008, click Visual C# under Project Types, and then click Console Application under Templates. Add the following code at the beginning of the Class1.cs file:

As @Servy has stated, there isn't any built-in functionality (that I know of, or can find) that can do what you want. However, there is a work-around (it's a bit of a hack, but it worked).

You can create your own buffer in memory, or on disk. Whenever you output to the Console, also output to your buffer. You can then use your buffer to read from in ways that you couldn't with the Console.

There are two ways to buffer: on disk or in memory. You can use the Console.BufferWidth and Console.BufferHeight properties to find out your buffer size. I found it simpler to do this in memory using an array of strings (each string was a line of output, and there were a number of strings in the array equal to the BufferHeight, if I remember correctly). A colleague ended up doing the same thing on disk.

You'll want to create a method to replace Console.Write and Console.WriteLine, so that you can write to both buffers at once. Something like:

public void MyWrite( string output ) {
    Console.Write( output );
    Array.Write( output );  // obvious pseudo-code
}

I found it helpful to wrap a Class around the array and implement methods to support it ... you could then implement your GetCharAtLocation( int i, int j ) method, as well as any other functionality you need there.

Console.ReadLine() Method in C#, Learn how to read a text file in C# using the File class and its methods. ReadAllLines(textFile);; foreach (string line in lines); Console. in it) on your machine and change the "textFile" variable to the full path of your .txt file. The next character from the input stream, or negative one (-1) if there are currently no more characters to be read. The following example demonstrates the Read method. // This example demonstrates the Console.Read() method. using namespace System; int main() { String^ m1 = " Type a string of text

What about:

class Program {
    static void Main( string[ ] args ) {
        CustomizedConsole.WriteLine( "Lorem Ipsum" ); //Lorem Ipsum
        Console.WriteLine( CustomizedConsole.ReadContent( 6, 5 ) ); //Ipsum
        Console.WriteLine( CustomizedConsole.GetCharAtLocation( 0, 0 ) ); //L
    }
}

static class CustomizedConsole {
    private static List<char> buffer = new List<char>();
    private static int lineCharCount = 0;

    public static void Write(string s){
        lineCharCount += s.Length;
        buffer.AddRange( s );
        Console.Write( s );
    }

    public static void WriteLine(string s ) {
        for ( int i = 0; i < Console.BufferWidth - lineCharCount - s.Length; i++ )
            s += " ";

        buffer.AddRange( s );
        Console.WriteLine( s );
        lineCharCount = 0;
    }

    public static string ReadContent( int index, int count ) {
        return new String(buffer.Skip( index ).Take( count ).ToArray());
    }

    public static char GetCharAtLocation( int x, int y ) {
        return buffer[ Console.BufferHeight * x + y ];
    }
}

EDIT :

As said the others this is just a trivial case where there are a lot of other things to improve. But I wrote this only as a starting point.

How To Read A Text File In C#, How to retrieve the Executable Path of a Console Application in C# WriteLine(​path); // Pause application to read the output in the console  Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } Compiling the Code. Copy the code and paste it into a C# console application. If you are not using the text files from How to write to a text file, replace the argument to ReadAllText and ReadAllLines with the appropriate path and file name on your computer. Robust

How to retrieve the Executable Path of a Console Application in C# , C# has a wide array of file operations. These operations include opening a file, reading or writing to a file. ReadAllLines(path); Console. By default, Visual C# creates a class that is named Program. Note In Visual Studio .NET 2003, click Visual C# Projects under Project Types, and then click Console Application under Templates. Name the project ConConfig. By default, Visual C# creates a class that is named Class1. Make sure that the Solution Explorer window is visible.

C# File I/O Handling Operations [Examples], C# User Input Type your username and press enter Console. Console.​WriteLine("Enter your age:"); int age = Console.ReadLine(); Console. While using this site, you agree to have read and accepted our terms of use, cookie and​  Logging to Standard Output (Console) and Debug Output (Trace) – Logging to Console, also known as Standard Output, is very convenient, especially during development. Windows also supports a similar logging target called Debug Output , which you can log to with System.Diagnostics.Trace("My message") .

C# User Input, Reading text files in C# shows how to read text files in C#. For instance, MemoryStream works with data located in the memory and The example reads the contents of the thermopylae.txt file and prints them to the console. In this post, we will learn how to get an application startup path from a console application using C#. Here is an example of getting the path. For this, we are using some namespace and Assembly for getting the path that is already added in this post. This example gets the path of application and display on the screen and waits for user key press.

Comments
  • Is this console application something you can modify?
  • Yes, i am developing the console application, if that's what you're asking.
  • Do you need to read from the actual window or from the buffer?
  • Usually, the need to do this is rare. If the user is providing input that you need to reference later, you should probably be storing that input in memory somewhere. Maybe if you can be more specific in a new question about your problem someone can offer an alternative solution.
  • Guys, I am trying to read data from a console application that is hosted inside a WPF application. So far I am able to read data from Console Application outside wpf by using ReadConsoleOutput but it only reads from ActiveConsole Buffer. How can i read from console that is hosted inside WPF application. Please help!
  • That is just a tad annoying. Oh well, disappointing answer (not your fault of course), but i guess not every rainbow has a pot of gold at the end. Thanks heaps for the help, i think i'll start considering other options now :P
  • I've tried this, but got an error: "System.IO.IOException: 'The handle is invalid."
  • @AndrásGeiszl - I've justed tested it and it still works fine, with .NET 4 to 4.7, or .NET Core, win10 x64 or x32, with cmd.exe or other console (like ConEmu).
  • I am getting error at out byte chAnsi ==> Invalid expression term byte. I am using Visual Studio 2015 .Net Framework 4.6.2
  • @FaranSaleem The example uses C# 7 features. You can declare the ‘out’ variables separately, instead of inline, or upgrade to VS2017 or VS2019.
  • Okay got it. I also have a console app embedded in another WPF Application. I am passing it the handle but it says invalid handle. With -11 I am only able to write on current console window. How can I fix this?