C#: 'System.IO.FileNotFoundException' and 'Debug profile does not exist' - c#

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.

Related

Can't input data with Console.ReadLine

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 ?

C# Console.ReadLine() never reads input on VSC in Linux

I've got a Console.ReadLine() inside a finite for loop that never ends reading.
I am using VS Code on Linux Mint. I execute by pressing F5.
using System;
class Person
{
public string Name { get; set;}
public override string ToString()
{
return "My name is " + Name;
}
}
class Program
{
static void Main(string[] args)
{
int n = 3;
Person[] p = new Person[n];
for (int i = 0; i < n; i++)
{
p[i] = new Person()
{
Name = Console.ReadLine()
};
Console.WriteLine("I just read " + p[i]);
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(p[i].ToString());
}
}
}
I expected to input three names and then output them.
I input by typing a name and then pressing Enter.
The issue is that I can keep inputting forever and that Console.WriteLine("I just read " + p[i]); never gets executed. This happens in the Debug Console.
I can't reproduce this on Windows or Ubuntu. My guess is that Mint buffers the output.
Try adding Console.Out.Flush(); after Console.WriteLine("I just read " + p[i]);
This is still an issue on Linux. Running Visual Studio Code, in debug mode. Output is being directed to Debug Console, but input is not being considered.
It only works when running from command line, but that basically disallows for debugging.
Though the answer for this problem is here
Debug Console window cannot accept Console.ReadLine() input during debugging

Getting output data from console application

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.

Error: 'The process cannot access the file because it is being used by another process' in Visual Studio c#

I am having some trouble with this error in Visual Studio:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\aheij\Desktop\KinectOutput\swipe.txt' because it is being used by another process.
What I Have tried:
I have tried using these codes obtained from other solved StackOverflow questions similar to mine to try to solve the problem - but even that didn't seem to work?
Ive tried checking if the file is in use, but with no success.
I also run Visual Studio as administrator.
The file is not read-only.
The folder is not open, and the file is not being used in any other program when executing the code - at least not that I can see/know of.
The code:
So, to add some context to my code: I am writing some quick gesture detection code to the Kinect c# BodyBasics SDK v2 code freely available. This is a helper method that I added, that gets called in when a person is in view. If that person is executing the gesture, the method writes the frame time and gesture name to a text file.
Half the time, when the code does work, the gesture recognition works well. However, the other half of the time, the code breaks/stops because the writing to file bit causes the error.
Below is my code to see if the person is standing in the neutral position - its a bit waffly, so apologies about that. I have commented 'ERROR' where the error is (unsurprisingly):
private void Neutral_stance(VisualStyleElement.Tab.Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
CameraSpacePoint left_hand = joints[JointType.HandLeft].Position;
CameraSpacePoint left_elbow = joints[JointType.ElbowLeft].Position;
CameraSpacePoint left_shoulder = joints[JointType.ShoulderLeft].Position;
CameraSpacePoint left_hip = joints[JointType.HipLeft].Position;
CameraSpacePoint right_hand = joints[JointType.HandRight].Position;
CameraSpacePoint right_elbow = joints[JointType.ElbowRight].Position;
CameraSpacePoint right_shoulder = joints[JointType.ShoulderRight].Position;
CameraSpacePoint right_hip = joints[JointType.HipRight].Position;
double vertical_error = 0.15;
double shoulderhand_xrange_l = Math.Abs(left_hand.X - left_shoulder.X);
double shoulderhand_xrange_r = Math.Abs(right_hand.X - right_shoulder.X);
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_p = #"C:\Users\aheij\Desktop\KinectOutput\Punch.txt"; //write to punch file
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt"; //write to swipe file
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
File.AppendAllText(path_p, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
File.AppendAllText(path_p, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
}
}
}
Any solutions/ideas/suggestions to point me on the right track would be appreciated. I think that it would be good to use the 'using streamwriter' method as opposed to the method I am using here - but I am not sure how? Any help would be appreciated.
Additonal Info: Using Visual Studio 2015; Using windows 10.
Sidenote: I read somewhere that the Windows Search tool in Windows 10 can interfere and cause problems like this so I need to disable it?
As suggested to me I used the Filestream method & ensured the file was closed after use. But, even this still caused the same error.
Thus, I also got rid of having two file-writing actions in rapid succession of each other. I dont know if this is technically right or even true, but based off of this post here: link, my error could be coming up because I am trying to execute the second 'write to text file' line whilst the previous 'write to text file' line is still executing/writing to that same folder & location - hence the clash? Please someone, correct me if I am wrong.
Either way, this seems to have worked.
See below for my edited/corrected method:
private void Neutral_stance(Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
//cameraspace point joint stuff here again (see original post for this bit leading up to the if statements.)
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt";
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
FileStream fs_s = new FileStream(path_s, FileMode.Append); //swipe
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Neutral" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
FileStream fs_s = new FileStream(path_s, FileMode.Append);
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Unknown" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
Do let me know if there is any way I can make this more elegant or anything else I should be aware of w.r.t this answer.
The code is based off of the code found here: FileStream Tutorial website

Visual Studio 2015 - EnvDTE Read ErrorList

I'm about to create a small Build Tool. The only things it should do: Try to Build the Solution and output the errors.
But not I have the following problem: In case the Build fails I cannot read the ErrorList. The program gets stuck and waits until forever.
I've created a small test Class which does nothing else than creating an instance of the Visual Studio 2015, build the given solution and read out the ErrorList on Build fail.
class Class1
{
DTE2 dte = (DTE2)System.Activator.CreateInstance(System.Type.GetTypeFromProgID("VisualStudio.DTE.14.0", true));
public void Test()
{
int id = dte.LocaleID;
//dte.MainWindow.Visible = true;
dte.Events.BuildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(BuildEvents_OnBuildDone);
string solutionFile = #"C:\MyProjects\SolutionWithBuildErrors.sln";
dte.Solution.Open(solutionFile);
while (!dte.Solution.IsOpen)
System.Threading.Thread.Sleep(100);
Console.WriteLine("Start Build");
dte.Solution.SolutionBuild.Build(true);
Console.WriteLine("Finished Build");
dte.Quit();
}
private void BuildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
{
Console.WriteLine("BuildEvents_OnBuildDone Called");
int buildInfo = dte.Solution.SolutionBuild.LastBuildInfo;
switch (buildInfo)
{
case 0:
Console.WriteLine("Build erfolgreich");
break;
case 1:
Console.WriteLine("Build fehlerhaft");
getErrorList();
break;
}
}
private void getErrorList()
{
//dte.ExecuteCommand("View.ErrorList", " ");
Console.WriteLine("Lade Tool Windows");
ToolWindows tw = dte.ToolWindows;
Console.WriteLine("Geladen, Tool Windows");
Console.WriteLine("Lade ErrorList");
ErrorList el = tw.ErrorList;
Console.WriteLine("Geladen, ErrorList");
el.ShowErrors = true;
Console.WriteLine("Lese Error Liste");
//dte.ExecuteCommand("View.ErrorList", " ");
//ErrorItems errors = dte.ToolWindows.ErrorList.ErrorItems;
Console.WriteLine("#Errors: " + dte.ToolWindows.ErrorList.ErrorItems.Count);
for (int i = 1; i <= dte.ToolWindows.ErrorList.ErrorItems.Count; i++)
{
ErrorItem ei = dte.ToolWindows.ErrorList.ErrorItems.Item(i);
string errorLevel = "N/A";
errorLevel = ei.ErrorLevel.ToString();
string desc = "N/A";
if (ei.Description != null)
desc = ei.Description.ToString();
string file = "N/A";
if (ei.FileName != null)
file = ei.FileName.ToString();
string line = "N/A";
line = ei.Line.ToString();
string error = string.Format("{0}: {1}, File: {2}, Line: {3}", errorLevel, desc, file, line);
Console.WriteLine(error);
}
}
}
For testing purposes, just create a console application. In the main:
Class1 c1 = new Class1();
c1.Test();
Console.ReadLine();
Necessary Imports:
EnvDTE
EnvDTE80
I've already tried to run the Visual Studio in Visible-Mode and in case the Visual Studio Instance gets the focus while in the "wait for ErrorList Read" the ErrorList can be read.
If the Visual Studio never gets the focus (because running invisible or never click into while running visible) its not possible to receive the ErrorList.
Maybe there is another way to read out the ErrorList?
Just found the Solution I'm using =(
Maybe you can help me out or verify that there are really troubles with the ErrorList.
This is another way to get at the ErrorList - if that's really your problem:
EnvDTE.Window window = this.dte.Windows.Item(EnvDTE80.WindowKinds.vsWindowKindErrorList);
EnvDTE80.ErrorList sel = (EnvDTE80.ErrorList)window.Selection;
But both ways should be fairly equivalent. Microsoft did re-write Error List window implementation for VS 2015 - introducing some issues in the process, so I'd suggest trying your code against earlier versions.
Whether this issue has been Resolved or not I don't Know, But If its Exist Then Proceed with the ActiveX Concept To Solve this issue(More or less you can proceed with User Control ). Sure this issue will resolve I have done the same for my requirement.No need to Keep Focus on the respective Visual Studio

Categories

Resources