Wait for multiline console input to finish c# - 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

Related

How to pass file to the program from the command line

I am writing a wpf application which should draw lines due points given in a file.
How can I pass a file in the command line to my c# program?
For example something like
MyProgram.exe < file.txt
In addition how can I do this in visual studio for debugging?
I know I can set command line args and can read them with
var args = System.Environment.GetCommandLineArgs().ToList();
You have to do is call the program in this way, "filedetails.exe myfile.txt"
Example :
C:\Users\FILEREADER>filedetails.exe myfile.txt
How can I pass a file in the command line to my c# program? For example > something like
MyProgram.exe <file.txt
You can try this Console.OpenStandardInput()
I don't think it is possible to pass file content as a parameter. You currently pass file content correctly:
MyProgram.exe < file.txt
all you need is to read it, I put a small cmd application:
static void Main()
{
string line;
while ((line = Console.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
In wpf application:
public MainWindow()
{
InitializeComponent();
var result = "";
string line;
while ((line = Console.ReadLine()) != null)
{
result += (line);
}
MessageBox.Show(result);
}
Check here for more information about about command line redirections.

Illegal characters in path from class

I'm stuck in a stupid error but I can't figure it out, could you please help me out?
What
I'm trying to create a class that will have several methods which will perform many different regex in a given text file. This text file is passed in from the main program to the class.
The class then consumes the text file and perform each regex where I call from the main program by instantiating each object in the class.
Problem
When I pass the file, I created a function within the class to count the lines of the file and loop through each line counting how many times such regex match happens.
//CountLines Function
static long CountLinesInFile(string f)
{
long count = 0;
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
count++;
}
return count;
}
}
This CountLines function will provide the lines to be looped through by the object as in:
private string configfile;
public string ConfigFile
{
get { return this.configfile; }
set { this.configfile = value; }
}
public void objects()
{
//Counting Object Group Network
int objCount = Lines(configfile)
.Select(line => Regex.Matches(line, #"object-group network").Count)
.Sum();
//Ending of Counting Object Group Network
}
from the main program Im trying to call the class and get the results by doing this:
Cisco newCisco = new Cisco();
newCisco.ConfigFile = richTextBox1.Text;
newCisco.objects();
I'm getting stuck at the class at the using (StreamReader r = new StreamReader(f)) line with an Illegal characters in path:
Exception:Thrown: "Illegal characters in path." (System.ArgumentException)
A System.ArgumentException was thrown: "Illegal characters in path."
Time: 8/13/2014 1:58:01 AM
Thread:Main Thread[1304]
I know that I'm making a mistake but I can find where, and would appreciate if you could help me finding a solution for this issue.
The error you are receiving is most likely caused by the file name you are trying to open the StreamReader with, which I presume is invalid. Would you please post the filename you are trying to read, if checking it doesn't solve your problem?

Getting an index outside bound of an array in C#

This program is supposed to show the path of a directory and the directory if its exists then it should also show the files inside with the following extensions (i.e .doc, .pdf, .jpg, .jpeg) but I'm getting an error
*Index was outside the bounds of the array.
on this line of code
string directoryPath = args[0];
This is the code in the main function
class Program
{
static void Main(string[] args)
{
string directoryPath = args[0];
string[] filesList, filesListTmp;
IFileOperation[] opList = { new FileProcNameAfter10(),
new FileProcEnc(),
new FileProcByExt("jpeg"),
new FileProcByExt("jpg"),
new FileProcByExt("doc"),
new FileProcByExt("pdf"),
new FileProcByExt("djvu")
};
if (Directory.Exists(directoryPath))
{
filesList = Directory.GetFiles(directoryPath);
while (true)
{
Thread.Sleep(500);
filesListTmp = Directory.GetFiles(directoryPath);
foreach (var elem in Enumerable.Except<string>(filesListTmp, filesList))
{
Console.WriteLine(elem);
foreach (var op in opList)
{
if (op.Accept(elem)) op.Process(elem);
}
}
filesList = filesListTmp;
if (Console.KeyAvailable == true && Console.ReadKey(true).Key == ConsoleKey.Escape) break;
}
}
else
{
Console.WriteLine("There is no such directory.");
}
}
}
How can I handle this error it seems to be common but it happens id different ways
You need to pass the necessary arguments to the program when running it. You can either do this by running the program from the command line, or else when running Visual Studio by doing the following:
Right click on project
Properties
Debug tag
Enter arguments under Start Options -> Command line arguments
You might want to pass the arguments into the program from command line.
like this:
> yourProgram.exe directoryName
Also, to avoid such problems in the code,
if(args.Length > 0){
string directoryPath = args[0];
}else{
//print a help message and exit, or do something like set the
//default directoryPath to current directory
}
Do you want the user to enter a path when the program starts or when they start the program? If it's the first, then you should add a Console.Read() method that asks for the path.
If it's the latter, then you need to pass the path as an argument when starting the program. You should also do a check against the args array before reading from it to check that it contains data and that data is a valid path.
Something like:
if(args.Length > 0 && Directory.Exists(args[0]))
{
// Do Something.
}

How to write in current line of Console?

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.

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