How to write in current line of Console? - c#

I am writing a console application and I need to know, how to write in current line with shift of lines. I try to explain this on the next example:
Let It console lines with their numbers and contents along with cursor position.
Hello!
This is my command shell.
Please write something: _
When I call my method for writing in console text "lalala", i want to see that:
Hello!
This is my command shell.
lalala
Please write something: _
If I use Console.WriteLine method I see the next:
Hello!
This is my command shell.
Please write something: lalala
_
Please, help me to realise this feature.

Console.SetCursorPosition is the poison you are look for.
More details on http://msdn.microsoft.com/en-us/library/system.console.setcursorposition.aspx

As you didn't provide any code i assume you're using Console.WriteLine("Please write something"); to print out text. Since this will add an \n to the text you want to print you should rather use Console.Write("Please write something") then do an Console.ReadLine(); to get the input and handle the \n by yourself.

Console.WriteLine("1.Hello!");
Console.WriteLine("2.This is my command shell.");
Console.WriteLine("3.lalala");
Console.Write("4.Please write something:");
Console.Read();

If I understand your question right I think you need to use
Console.Write("text");
This will write on the same line as the cursor is currently on.
Rather than:
Console.WriteLine("text");
This will create a new line in the console each time it is called.

Please find the code for the above scenario:
private static void ReadAndWriteToConsole()
{
var mystrings = new List<string>();
mystrings.Add("Hello!");
mystrings.Add("This is my command shell.");
var input = WriteToConsole(mystrings);
while (input.ToLower() != "exit")
{
mystrings.Add(input);
Console.Clear();
input = WriteToConsole(mystrings);
}
}
private static string WriteToConsole(IEnumerable<string> variables )
{
foreach (var str in variables)
{
Console.WriteLine(str);
}
Console.Write("Please write something:");
return Console.ReadLine();
}
Hope that helps.
NOTE: If you want the number of each string then use a for loop instead of foreach and just print the variable used in the console.writeline.

try something like this
Console.Write("Hello\nThis is My Command Shell\nlalala\nPlease Enter Something:___");
if course that would end up having them all appear at the same time, but if your good with that this will work
Will look like this

I realize that this is an old question, however I have been searching this stuff and here is how it can be coded:
Console.WriteLine("Hello!");
Console.WriteLine("This is my command shell.");
string text = "";
string toWrite = "Please write something: ";
while (text != "quit")
{
Console.Write(toWrite);
text = Console.ReadLine();
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.WriteLine(text.PadRight(text.Length + toWrite.Length));
}
The Console.SetCursorPosition puts the cursor back to the line that was written into, then overwrite what is written with the text and a padding equivalent to how many chars the text had.

Related

Wait for multiline console input to finish c#

I am supposed to write a program where the user inputs a maze and my application tries to find a way to navigate through it. The input of the maze is supposed to be something like
#####
#...#
#...#
#####
And I am supposed to use Console.OpenStandardInput(), and the user copy pastes the maze into the console. However, when I use Console.ReadLine() to wait for the user to copy paste the maze, it only reads the first line. I know for Java you just make a new Scanner(System.in), but how do I do this in c#?
EDIT:
My entire code is
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
for (int i = 0; i < 5; i++)
{
Console.Write((char)sr.Read());
}
Console.WriteLine("done");
Console.ReadKey();
}
}
When I copy and paste in
AB
CD
From Notepad, the output becomes
AB
AB
CDcursor here
Console.ReadLine() return after every single line so you need to use loop to read all line from console till you will get null
List<string> lines = new List<string>();
string line;
while ((line = Console.ReadLine()) != null)
{
// Either you do here something with each line separately or
lines.add(line);
}
// You do something with all of the lines here

Catching File Exceptions using c#

The below is what I am wrestling with today using Visual Studios Console App.
What I want to happen, which currently isn't, is when the Console App opens, and I type the first "checksPath" in, if this turns out to not exist, I want it to say that the path is wrong, and either, let the user try again, or close the app. If the path is valid, then it moves onto the next "reportDest", and the same applies. If it's an invalid path, I want a message saying so, with the option of trying again, or closing the app. If both paths entered (eventually) are valid, I want a message to say that the report will now produce. The rest of the script that produces the report is perfectly fine, it's just the bit i've put below that's troublesome.
string checksPath;
Console.Write("Please enter the source path for the Checks Workbook, including the name of the file (Not including the file extension): ");
checksPath = Console.ReadLine() + ".xlsx";
try
{
if (File.Exists("checksPath"))
throw new FileNotFoundException();
}
catch (FileNotFoundException e)
{
Console.WriteLine("Invalid path - Please close the app and try again!");
Console.ReadLine();
}
string reportDest;
Console.Write("Please enter the folder location and file you wish your report to go to (Not including the file extension): ");
reportDest = Console.ReadLine() + ".xlsx";
try
{
if (File.Exists("reportDest"))
throw new FileNotFoundException();
}
catch (FileNotFoundException e)
{
Console.WriteLine("Invalid path - Please close the app and try again!");
Console.ReadLine();
}
Console.WriteLine("Your report will now produce");
Since you need to continually ask a question until the user gets it right, you will need a loop. Next in that loop you need to check if the path exists.
bool run = true;
while (run)
{
Console.Clear();
Console.WriteLine("Enter Path:");
string answer = Console.ReadLine();
if (Directory.Exists(answer)) run = false;
else
{
Console.WriteLine("Path Does not exists. Try again. Press enter to continue...");
Console.ReadLine();
}
}

I want to read from and write to a file in C#

here is my code without files
static void Main(string[] args)
{
// BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
BluetoothClient bc = new BluetoothClient();
BluetoothDeviceInfo[] devs = bc.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo d in devs)
{
System.Console.WriteLine(d.DeviceName);
}
System.Console.WriteLine("finish");
System.Console.ReadLine();
}
Instead of the line System.Console.WriteLine(d.DeviceName);
I want that part to be written into a file.
After that I need to loop on that file, and for each device name in that file, I will search in another file for it's corresponding output. A hint on how to loop on and search in files will be sufficient for that part.
Thank you.
You can use File.AppendAllText() as an exact drop-in (but you'll need to append Environment.NewLine to your text).
Make sure that you delete the file if it exists before your foreach loop, possibly prompting the user for confirmation depending on your requirements.

Bulk replace or remove a character in file names

I have a little utility I'm writing that will let the user replace 1 character for another in a filename from a specific directory the user chooses.
The idea is to let the user replace an "_" or any other character they want with any other character they want or just remove it altogether.
EDIT: After taking the information I learned from your responses and a little Google searching to understand how those commands worked, I came up with this code. Any feedback would be nice.
private static void myremovechar()
{
//subprocedure to modify file names by removing or replacing characters NO SUB DIRECTORIES
//Ask user where the files are located and store value in string mybadfilesource
Console.Clear();
Console.WriteLine("Where are your files located");
Console.WriteLine(#"Example: D:\folder\subfolder\");
string mybadfilesource = Console.ReadLine();
//Ask user what character to remove and store value in string mychartodelete
Console.WriteLine("What character do you want to remove");
Console.WriteLine("Only 1 Character allowed");
string mychartodelete = Console.ReadLine();
//Ask user what character to replace mychartodelete with and store value in string mychartoreplace
//if user just hits enter, mychartodelete will just be deleted
Console.WriteLine("What character do you want to replace it with");
Console.WriteLine("Press enter to just delete previously selected Character");
Console.WriteLine("Only 1 Character allowed");
string mychartoreplace = Console.ReadLine();
try
{
//store list of files from mybadfilesource in var filelist
var filelist = Directory.EnumerateFiles(mybadfilesource);
foreach (string file in filelist)
{
//renames the files by Replacing mychartodelete with mychartoreplace
var newfile = string.Format("{0}{1}",Path.GetFileNameWithoutExtension(file).Replace(mychartodelete, mychartoreplace),Path.GetExtension(file));
File.Move(file, Path.Combine(mybadfilesource, newfile));
}
}
//Error Checking Process - Prints error message
catch (Exception e)
{
Console.WriteLine(e.Message);
}
//tell user the process is done and return to Main Menu
Console.WriteLine("Finished - Press Enter to Return to Main Menu");
Console.ReadLine();
Console.Clear();
Main();
}
Thank you all for your help
There's a lot of wrong here:
You're calling Replace on the wrong variable
If you use the right variable, you'll still get an error for modifying a variable in a foreach loop
You're not really renaming anything, you're not applying anything back to the actual file.
try this:
foreach (var file in Directory.EnumerateFiles(mybadfilesource))
{
var newfile = string.Format("{0}{1}",
Path.GetFileNameWithoutExtension(file).Replace(mychartodelete, mychartoreplace),
Path.GetExtension(file));
File.Move(file, Path.Combine(mybadfilesource, newfile));
}
Be sure to just get the filename without the path or extension, or else you'd be changing those too

C# Problem Reading Console Output to string

i want to launch ffmpeg from my app and retrive all console output that ffmpeg produces. Thing seems obvious, i followed many forum threads/articles like this one but i have problem, though i follow all information included there I seem to end up in dead end.
String that should contain output from ffmpeg is always empty. I've tried to see where is the problem so i made simple c# console application that only lists all execution parameters that are passed to ffmpeg, just to check if problem is caused by ffmpeg itself. In that case everything work as expected.
I also did preview console window of my app. When i launch ffmpeg i see all the output in console but the function that should recieve that output for further processing reports that string was empty. When my param-listing app is launched the only thing I see is the expected report from function that gets output.
So my question is what to do to get ffmpeg output as i intended at first place.
Thanks in advance
MTH
This is a long shot, but have you tried redirecting StandardError too?
Here is a part of my ffmpeg wrapper class, in particular showing how to collect the output and errors from ffmpeg.
I have put the Process in the GetVideoDuration() function just so you can see everything in the one place.
Setup:
My ffmpeg is on the desktop, ffPath is used to point to it.
namespace ChildTools.Tools
{
public class FFMpegWrapper
{
//path to ffmpeg (I HATE!!! MS special folders)
string ffPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ffmpeg.exe";
//outputLines receives each line of output, only if they are not zero length
List<string> outputLines = new List<string>();
//In GetVideoDuration I only want the one line of output and in text form.
//To get the whole output just remove the filter I use (my search for 'Duration') and either return the List<>
//Or joint the strings from List<> (you could have used StringBuilder, but I find a List<> handier.
public string GetVideoDuration(FileInfo fi)
{
outputLines.Clear();
//I only use the information flag in this function
string strCommand = string.Concat(" -i \"", fi.FullName, "\"");
//Point ffPath to my ffmpeg
string ffPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ffmpeg.exe";
Process processFfmpeg = new Process();
processFfmpeg.StartInfo.Arguments = strCommand;
processFfmpeg.StartInfo.FileName = ffPath;
//I have to say that I struggled for a while with the order that I setup the process.
//But this order below I know to work
processFfmpeg.StartInfo.UseShellExecute = false;
processFfmpeg.StartInfo.RedirectStandardOutput = true;
processFfmpeg.StartInfo.RedirectStandardError = true;
processFfmpeg.StartInfo.CreateNoWindow = true;
processFfmpeg.ErrorDataReceived += processFfmpeg_OutData;
processFfmpeg.OutputDataReceived += processFfmpeg_OutData;
processFfmpeg.EnableRaisingEvents = true;
processFfmpeg.Start();
processFfmpeg.BeginOutputReadLine();
processFfmpeg.BeginErrorReadLine();
processFfmpeg.WaitForExit();
//I filter the lines because I only want 'Duration' this time
string oStr = "";
foreach (string str in outputLines)
{
if (str.Contains("Duration"))
{
oStr = str;
}
}
//return a single string with the duration line
return oStr;
}
private void processFfmpeg_OutData(object sender, DataReceivedEventArgs e)
{
//The data we want is in e.Data, you must be careful of null strings
string strMessage = e.Data;
if outputLines != null && strMessage != null && strMessage.Length > 0)
{
outputLines.Add(string.Concat( strMessage,"\n"));
//Try a Console output here to see all of the output. Particularly
//useful when you are examining the packets and working out timeframes
//Console.WriteLine(strMessage);
}
}
}
}

Categories