I am new to .NET programming. I referred to a tutorial while creating this project. I have a dll file that does add and subtract functions:
ClassLibraryDll.dll
public class MathClass
{
//method for Addition
public static long Add(long num1, long num2)
{
return num1 + num2;
}
//method for Subtraction
public static long Sub(long num1, long num2)
{
return num1 - num2;
}
}
I have an .NET Console Application which has a program class which will make reference to the dll file and will use the functions from the dll file and take in two integers as input and display an output according to the function chosen.
Program.cs
using ClassLibraryDll;
class Program
{
static void Main(string[] args)
{
MathClass.Add(10, 10);
Console.WriteLine("Calling methods from ClassLibraryDLL:");
if (args.Length != 2)
{
Console.WriteLine("Usage: TestCode <num1> <num2>");
return;
}
long num1 = long.Parse(args[0]);
long num2 = long.Parse(args[1]);
long sum = MathClass.Add(num1, num2);
long substract = MathClass.Sub(num1, num2);
Console.WriteLine("{0} + {1} = {2}", num1, num2, sum);
Console.WriteLine("{0} * {1} = {2}", num1, num2, substract);
}
}
The output I am suppose to get assuming 1 and 1 are entered as command line args:
Calling methods from ClassLibraryDll:
1 + 1 = 2
1 - 1 = 0
I am unsure how to get the output from the console application. When I run the console application, I am unable to input any integers.
enter image description here
Someone please help me. Thank you so much in advance.
I think you're looking for the Console.ReadLine method, which waits for the user to input a line of text.
The command line args are used mainly when starting an application automatically from another application, or from a shortcut link etc, and I think are the wrong option for this kind of problem.
Hope this helps!
Looks like you're trying to call run the 'executable' file without the required arguments.
To run an executable file with arguments, you need to do the following.
1) Start the command prompt.
(Windows Key + R -> cmd)
2) Change current directory to your Console Application projects 'Debug' folder
(Eg., cd C:\YourProjectFolder\bin\debug)
3) Enter name of executable with arguments
(Eg., C:\YourProjectFolder\bin\debug>YourExecutableName 1 1)
If you insist on running from Visual Studio, you need to open your project's properties, click the Debug tab and enter your numbers as Command line arguments. You will not be able to see the results unless you add a Console.ReadLine() at the end of your program. I often do this:
if (System.Diagnostics.Debugger.IsAttached)
{
Console.Write("Press <Return>");
Console.ReadLine();
}
If run from inside Visual Studio, if will wait for a Carriage Return, otherwise not.
Related
I'm trainning in C# alone for this moment, and encounter my first problem.
I use VSCode as IDE.
What I Am Try To Do
Create two functions, the first, data like name and return it. the second return full name. All in one in a class.
What I Do From Here
using System
namespace Helloworld
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine(p.getFullName())
}
public string getName(string message)
{
string? name;
do
{
Console.WriteLine(message);
name = Console.ReadLine();
}
while (string.IsNullOrEmpty(firstName)); // For avoid null or empty string, I'm not found another solution.
return name;
}
public string getFullName()
{
const string firstNameMessage = "Enter your first name: ";
const string lastNameMessage = "Enter yout last name: ";
string result = $"{getName(firstNameMessage)} {getName(lastNameMessage)}"
return result;
}
}
}
I Have Encountered Any Problems
1 - When I launch the command dotnet run, my program follow instructions while the first Console.WriteLine. When I type an random name in VSCode's Debug Console. Nothing happens...
My questions: Does this problem come my code ? Am I using an unsuitable IDE ? Or Am I not working with the good VSCode's Tools ?
2 - When I want restart or build I have a message like The process cannot access the file C:\Users\Username\ Documents\Work\learningCSharp\bin\Debug\net6.0\learningCSharp.dll' because it is being used by another process.
My question: How I kill process which use my DLL file ?
I solve all my problem finally alone. I read here the solution.
I'm posting the solution anyway.
in your launch.json replace "console": "internalConsole" by "console": "integratedTerminal.
If you are senior in C#, Can you tell us if is it same for all IDEs ?
EDIT: It turns out that the local variable was not the issue. Even after changing it I get the error message from Visual Studio Community (was using VS code before):
"An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module. Could not load file or assembly 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
If I create a new project, and copy and paste the code, a different message appears:
The debug executable 'D:\Desktop\New folder\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp3.1\ConsoleApp1.exe' specified in the 'ConsoleApp1' debug profile does not exist
A problem also appears saying the program does not contain a Static Main, but the previous replies say the code works as it is.
OLD:
At college we have done a C# exercise (code will be further down) that for some reason does not work on my computer, despite being exactly the same (I have even copy and pasted someone else's that did work on theirs but not on mine). The code was meant to accept a number from the user and see if it was within a range or not, and depending on that output a message.
For some reason, it appears that a local variable is not being read as it shows up as the wrong color, but if you hover the mouse over the word, a pop-up menu does say it is a local variable. The variable is the 'result' after the 'if' and before the brackets (line 15).
At first we thought it was a problem with Visual Studio Code, so I tried it on Visual Studio Community 2019 and it still did not work. I already have the relevant framework. My teachers think there is a problem with my device, what do you think?
Here is how it looks in VS code
Here is the pop-up menu that appears
Here are the list of problems after debugging
And here is the source code:
using System;
namespace Csharp_learning
{
class MainDemo
{
static int ReadNumber(string prompt, int min, int max)
{
int result = 0;
do
{
Console.Write(prompt);
string numberString = Console.ReadLine();
result = int.Parse(numberString);
if result (result > max || result < min)
Console.WriteLine("Please enter a value in the range " + min + " to " + max);
else
break;
}
while(true);
return result;
}
}
}
This is my first time using this website, sorry if I did not present this correctly.
using System;
namespace Csharp_learning
{
class MainDemo
{
public static int ReadNumber(string prompt, int min, int max)
{
int result = 0;
do
{
Console.Write(prompt);
string numberString = Console.ReadLine();
result = int.Parse(numberString);
if (result > max || result < min)
Console.WriteLine("Please enter a value in the range " + min + " to " + max);
else
break;
}
while (true);
return result;
}
}
}
You have an extra result before if statement.
As for the other error you can try the link below.
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module
A problem also appears saying the program does not contain a Static Main, but the previous replies say the code works as it is.
Every c# console program has a static main. I was under the impression you already knew that. That part should look a little like below.
using System;
namespace Csharp_learning
{
class Program
{
static void Main(string[] args)
{
MainDemo.ReadNumber("Prompt input ", 1, 10);
}
}
}
These two different code blocks are most often in different files but you could just try copying in below to see if it works.
using System;
namespace Csharp_learning
{
class MainDemo
{
public static int ReadNumber(string prompt, int min, int max)
{
int result = 0;
do
{
Console.Write(prompt);
string numberString = Console.ReadLine();
result = int.Parse(numberString);
if (result > max || result < min)
Console.WriteLine("Please enter a value in the range " + min + " to " + max);
else
break;
}
while (true);
return result;
}
}
}
namespace Csharp_learning
{
class Program
{
static void Main(string[] args)
{
MainDemo.ReadNumber("Prompt input ", 1, 10);
}
}
}
Your code runs fine for me. It works as expected. The error suggest there is a typo in the project file. Open your CSharp Learning.csproj project file and look for parenthesis that are mismatched or out of place. Another solution would be to create a new project. Then copy your code the the new project.
I would like to have commands within the executable itself for example:
shorten http://stackoverflow.com/
and the url will be parsed as an argument, if I set it to return the argument, it should return me http://stackoverflow.com/
Another example is
foo bar
and it will check what is the main command which is foo and subcommands under it, which is bar and will execute the command.
This should be done within the executable and not calling the executable in the directory. I would like to have multiple custom commands within the executable and not create one for each command.
I understand how to have arguments if each command was an executable, but I would like a few commands and subcommands within 1 executable. Is this possible?
EDIT:
This is what I want:
static void Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "short")
{
Console.WriteLine(args[i + 1]);
}
}
Console.Read();
}
which will return me the arguments of short. So if I type short link it will return me link.
However this will only work if I call the executable through the command line like C:\Path\ConsoleApplication1.exe not if I open up the application and type short link, which will not return me anything and close.
How do I make it work when I open up the application and type it in?
You can use Console.ReadLine:
var input = Console.ReadLine();
To get command and argument(s) use String.Split :
var command = input.Split()[0];
var argument1 = input.Split()[1];
etc.
My program allows the user to put in 20 prices and to display the average of those values. Why does the console close after I enter my last input? Below is the code I'm running:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace machineproblem4
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
double average = 0;
Console.WriteLine("\t\t\t INPUT PRICES \n");
int[] price = new int[20];
Console.WriteLine("\t\t\t Please enter 20 prices \n");
for (int ctr = 0; ctr < 20; ctr++)
{
Console.Write("Enter price {0} : ", ctr + 1);
price[ctr] = Convert.ToInt32(Console.ReadLine());
}
// [...calculate sum...]
//average
Console.WriteLine("\n----------------------------");
Console.WriteLine("||average of the prices||");
average = sum / 20;
Console.WriteLine("average of the prices: {0}", average);
//more code that outputs statistics about the inputs
//exit
//Edit: This is what fixed my problem
Console.WriteLine("press any key to exit ..");
Console.ReadKey();
}
}
}
use Console.Readline();
Read(), ReadLine() and ReadKey() are basically static methods, and they comes under the Console class. That's why we use these methods like:
Console.Read():-- method accept the String and return the integer.
Console.ReadLine():--method accept the String and return string .
Console.ReadKey():--method accept the Character and also return Character.
That's why we mostly use the Console.ReadKey() method, for come back to source code from output window .
Because when we only press the character we directly come on source code. If you will use the Console.Read() and Console.ReadLine method then
you need to press Enter, come back to the source code rather then any character.
You can place a Console.Read() at the last statement. You can also place a breakpoint at your last statement
Generally, it is not a good idea to wait for user input from a console application. This is okay for debugging, but not definitely for release.
So, first find out if your application is in debug or release config using
private static bool IsDebug()
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(DebuggableAttribute), false);
if ((customAttributes != null) && (customAttributes.Length == 1))
{
DebuggableAttribute attribute = customAttributes[0] as DebuggableAttribute;
return (attribute.IsJITOptimizerDisabled && attribute.IsJITTrackingEnabled);
}
return false;
}
Then use,
if (IsDebug())
Console.Readline();
This eliminates the need to edit the code for different build configurations. Alternative is to put a breakpoint and debug the console app, as suggested by #Erwin
Put:
Console.Readline();
at the end of your main function, so it waits until you press enter before it closes.
None of the previous answers actually directly answer the question of why this is happening. The reason why the console is closing after your last input is that the rest of the code runs very quickly and when it reaches the end of your program, the console closes. This is correct behavior and should be expected when running a console application. As the other answers have stated, you can work around this by requiring a final input before closing the console, but that is all it is, a work around.
If you were to output to a text file rather than just the console, you would see that all of the output is generated as you would expect. The console output and close is just too fast for you to see it without some sort of pause in the code.
Additionally, a solution that has not been mentioned yet is to run the project from Visual Studio without debugging, which will automatically output "Press any key to continue..." when it finishes processing before closing the console. That way you can see what it is outputting without extraneous code that you wouldn't want to have in production code.
I want to build console application with similar interface like htop's one (fixed console design). Here is a link to htop console design: http://upload.wikimedia.org/wikipedia/commons/b/b1/Htop.png. I wanted to ask how can I build application like this as I only know C#'s Console.Write() method. I am writing simple program that is starting up applications via Process.Start() and then I am monitoring for example their RAM usage via Process.WorkingSet64 and outputing it via simple Console.WriteLine() each line to console. But how could I design C# console application like htop so it has fixed design that will be for example refreshing every 1 second. By fixed designed I mean that I it will be fixed position on the console where I will print out process names, ram usage, application name, etc. Here is my code of the program:
class Program
{
static void Main(string[] args)
{
string[] myApps = { "notepad.exe", "calc.exe", "explorer.exe" };
Thread w;
ParameterizedThreadStart ts = new ParameterizedThreadStart(StartMyApp);
foreach (var myApp in myApps)
{
w = new Thread(ts);
w.Start(myApp);
Thread.Sleep(1000);
}
}
public static void StartMyApp(object myAppPath)
{
ProcessStartInfo myInfoProcess = new ProcessStartInfo();
myInfoProcess.FileName = myAppPath.ToString();
myInfoProcess.WindowStyle = ProcessWindowStyle.Minimized;
Process myProcess = Process.Start(myInfoProcess);
do
{
if (!myProcess.HasExited)
{
myProcess.Refresh(); // Refresh the current process property values.
Console.WriteLine(myProcess.ProcessName+" RAM: " + (myProcess.WorkingSet64 / 1024 / 1024).ToString() + "\n");
Thread.Sleep(1000);
}
}
while (!myProcess.WaitForExit(1000));
}
}
EDIT: Thanks for pointing to Console.SetCursorPosition #Jim Mischel. I want to use that in my application but now I have another problem. How could I pass to my StartMyApp method, the index number from myApps array so I could do something like:
Console.WriteLine((Array.IndexOf(myApps, myAppPath) + " " + myProcess.ProcessName+" RAM: "+ (myProcess.WorkingSet64 / 1024 / 1024).ToString() + "\n");
That is inside my StartMyApp method. Any method I use I end up getting The name 'myApps' does not exist in the current context. This is very important for me so I could design my application later using Console.SetCursorPosition but I need that index number. So my output would be for example:
0 notepad RAM: 4
1 calc RAM: 4
2 explorer RAM: 12
You want to call Console.SetCursorPosition to set the position where the next write will occur. The linked MSDN topic has a basic example that will get you started.
You'll also be interested in the BackgroundColor, ForegroundColor, and possibly other properties. See the Console class documentation for details.