1

Is there any way that i can edit/rewrite certain lines that have already bin printed by the Console.PrintLine() method? I have to be able to edit any line that is shown in the prompt.

This is an example on what the code that i'm trying to get running, maybe can look like:

public static void RewriteLine(LineNr, Text)
{
    //Code
}

Console.WriteLine("Text to be rewritten");
Console.Writeline("Just some text");
RewriteLine(1, "New text");

Example to show which line that i want rewritten based on output from the previous code:

Text to be rewritten //This line (has already bin executed by the Console.WriteLine() method) shall be replaced by: "New text"

Just some text

augu0454
  • 45
  • 7
  • You're asking how to change source code while a program is running? Sounds like you need to use variables and programmaticially set the value of those variables _before_ displaying them. – D Stanley Dec 22 '15 at 20:36
  • 2
    @DStanley, I think he wants to overwrite the first line of output with "New text"--that is, to be able to write at arbitrary locations in the console window. – adv12 Dec 22 '15 at 20:37
  • 2
    There are some "hacky" ways to do it... see here: http://stackoverflow.com/questions/888533/how-can-i-update-the-current-line-in-a-c-sharp-windows-console-app – Rick Liddle Dec 22 '15 at 20:37
  • @DStanley No... I am asking how to change the text that the Console.WriteLine() method shows. But after the text has bin executed. I know how to delete certain lines, but not how to replace it by some other text. – augu0454 Dec 22 '15 at 20:39
  • Now it's more confusion. –  Dec 22 '15 at 20:40
  • @RickLiddle That did not solve my problem since it only explains how to rewrite the current line. I wanna know how to rewrite _any_ line that has bin executed. – augu0454 Dec 22 '15 at 21:10

1 Answers1

7

It should look like this:

public static void RewriteLine(int lineNumber, String newText)
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, currentLineCursor - lineNumber);
    Console.Write(newText); Console.WriteLine(new string(' ', Console.WindowWidth - newText.Length)); 
    Console.SetCursorPosition(0, currentLineCursor);
}

static void Main(string[] args)
{
    Console.WriteLine("Text to be rewritten");
    Console.WriteLine("Just some text");
    RewriteLine(2, "New text");
}

What's happening is that you change cursor position and write there something. You should add some code for handling long strings.

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164