Alright so I'm pretty new to programming in C#, and programming in general, and I decided to learn the programming language so I'm watching a youtube tutorial and writing everything in the same way as the guy in the video.
The only issue is that when I debug, I'm missing a few lines in the debug window.
I wrote 4 Console.WriteLine commands yet it only shows 2 of them in the debug window.
Example (current and expected):
https://gyazo.com/d363af46a05b804b65a927e9b075b6e4 (What I get when I debug)
https://gyazo.com/3fd4eed9d68983304b5098c9f07f809a (What I should be getting)
This might be a very popular issue that has been solved many times, but I haven't been able to find it since I don't know what to type specifically to find the solution to my problem.
I hope someone can help me. And again, the reason why the title of the question isn't specific is because I don't really know what I'm talking about so I'm relying on the images being enough.
The Code (has been moved from a comment of the author)
using System;
namespace Basics {
class Program {
static void Main(string[] args) {
string characterName = ("John");
int characterAge;
characterAge = 35;
Console.WriteLine("There one was a man named " + characterName);
Console.WriteLine("He was " + characterAge + " years old.");
Console.WriteLine("He really liked the name " + characterName);
Console.WriteLine("But didn't like being " + characterAge);
Console.ReadLine();
}
}
}
I have ran your code and it compiles fine. All four lines print.
You can try going to the solution explorer panel on the right -> right click your solution, -> Clean -> Rebuild. Then re-compile
Long time i work whit console..
But it pretty much working c# 8.0
namespace Basics
{
static class Program
{
static void Main() => ("John", 35).Story();
static void Story(this (string CharacterName, int CharacterAge) Infomation) {
Console.WriteLine("There one was a man named {0}", Infomation.CharacterName);
Console.WriteLine("He was {0} years old.",Infomation.CharacterAge);
Console.WriteLine("He really liked the name {0}", Infomation.CharacterName);
Console.WriteLine("But didn't like being {0}", Infomation.CharacterAge);
}
}
}
Related
Since yesterday evening my Application.persistenDataPath is not working anymore on one place in code. I am using it 2 times. On the first place it works on the second it doesnt work anymore...
Maybe a hint for you is, that I saved json very often yesterday. Also I had infinite loops what maybe caused the Application Settings to Crash.
On Android Build it is working fine. (I get the right Path on both usages)
What I have tried below the code
Both in the same Class.
Unity 2021.3.2f
Using Google Firebase
Visual Studio 2022 Community Edition
This the code where it works:
I am saving a Photo to the given Path.
//then Save To Disk as PNG
byte[] bytes = avatarTexture.EncodeToPNG();
var dirPath = Application.persistentDataPath + "/Resources/User/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
if (File.Exists(dirPath + "avatar" + ".png"))
{
File.Delete(dirPath + "avatar" + ".png");
}
File.WriteAllBytes(dirPath + "avatar" + ".png", bytes);
saveUserDataAsJson(getUserToken(user.DisplayName, user.Email));
_warningLoginText.text = "";
_confirmLoginText.text = Translation.authManager_login_notification_loginSucceeded;
This is the code where it does not work:
I am saving a JSON File with User Information.
DataSnapshot snapshotYear = taskYear.Result;
_year = Convert.ToInt32(snapshotYear.Value);
FirebaseDatabaseUser tempUser = new FirebaseDatabaseUser(_token, _day, _month, _year);
var json = JsonConvert.SerializeObject(tempUser);
Debug.Log("Can see it in Console");
//After pressing Play Button in Unity
//Editor i get no Debug outprint here
Debug.Log(Application.persistentDataPath);
var folderPath = Application.persistentDataPath + "/Resources/User/";
Debug.Log("Can not see it in Console");
//HERE THE CODE STOPS AND NOTHING HAPPEN
//NO ERROR NO LOG NO FURTHER CODE WORKING
//HERE NOT WORKING ANYMORE
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (File.Exists(folderPath + "userdata" + ".json"))
{
File.Delete(folderPath + "userdata" + ".json");
}
File.WriteAllText(folderPath + "userdata" + ".json", json);
I have tried:
rebuild Project Settings
Print the Path in Console it was empty ""
Cleaned GI Cache
Restarted my PC
Cloned the project new
Tried using Application.dataPath (only for debugging tests, not to use it in my code) also not working in Unity Play Mode but on Android it points right to the APK.
First usage (Place in Code where it works) I get Path:
Computer: C:\Users\{user}\AppData\LocalLow\{company}\{app}\Resources\User\
Android: .\Android\data\com.{company}.{app}\...\Resources\User\
Second usage (Place in Code where does not work) I get Path:
Computer: ""
Android: ".\Android\data\com.{company}.{app}\...\Resources\User\"
I hope someone can explain the issue. I cannot solve the problem from myself. Need someone who has more background knowledge.
so the anwer was based on the Help of #derHugo :
Some of the Unity API is using only the Unity main thread. Application.persistentDataPath is one piece of this Unity API elements.
So the problem was, that in the first code snippet i was using the Unity Main Thread, but in the second code snippet i used a Background Thread. Was really easy to fix. Instead of using another thread, i used:
`<myasyncfunction>.ContinueWithOnMainThread(task => {....
//second code snippet
})`
Refactoring tips of this Code:
File.Exists can be removed, it is totally redundant. WriteAllText creates or overwrites the file by default anyway.
The Construction of data paths over and over again makes no sense. Better way is to create public static readonly paths and use them instead.
Hope the Solution of #derHugo can help someone else.
Have a nice Day if you read this :)
Quick note: I come from python and other easier to use programming languages.
I dont know why it doesnt go and continue to the next line, this is the steps I took, I firstly run the script in visual studio and it runs and then I can input text into the debug console, I type something and it repeats the line of input so I input again and it doesnt go onto the next line it just loops at input = Console.ReadLine();, I even tried copying code from the internet that simply asks for input and prints it and it does the same thing, I think its something to do with visual studio maybe, This is a first so I apologize if I made a mistake, thank you for your help.
here is the code:
using System;
using System.IO;
namespace Printing
{
class Program
{
static void Main(string[] args)
{
string input;
Console.WriteLine("Please enter a number for the times table");
input = Console.ReadLine();
Console.WriteLine("number is: " + input);
for (int i = 0; i < 10; i++)
{
if (i != 0)
{
Console.WriteLine(i);
}
}
Console.ReadLine();
}
}
}
OMG This was very annoying and finally found a way of fixing this, for what ever reason the internal console does not work at all at least on my linux system, I found a post 4 years old mention changing the console to integratedTerminal and that fixed it, it works now, to change the console go to your launch.json file and change internalconsole too integratedTerminal.
very frustrating but now its done.
Something may be wrong with your Visual Studio. I've run your code in my computer and it works perfectly fine, nothing loops. Is VS updated to the latest version? Check Visual Studio Installer. And what console are you using? Is it the default Windows CMD? My advice would be to reinstall VS if it still doesn't work.
I'm new to this Page just now but already got a Question to ask.
Ok, I'm right now on a bigger Project (for me atleast) for a Server Interface of round about 3 Minecraft Servers on one machine.
Now I got to the point where I no longer want to call the startfiles manually, so i created a function that creates a Savefile with the location of the "servers" startfile (it's a simple batchfile) called "(name_of_server)_SAVEFILE(number_of_server).txt".
And now i want the Program to show me (best on startup) how many Servers actually have been saved by asking for the number talked about earlier.
I also want to implement a lock so the filenumber already created can't be saved with another name, but that's a different story there.
I did it like this:
private void checkForServer_button_Click(object sender, EventArgs e)
{
if (File.Exists(#"C:\Users\" + system_user + #"\Desktop\savedServers\*1.txt") == true)
{
string server1_location = File.ReadAllText(#"C:\Users\" + system_user + #"\Desktop\savedServers\*_SAVEFILE1.txt");
checkForServer_response.Text = "There are Servers!";
onlyInfo.Clear();
onlyInfo.Text = "[CONSOLE] Found existing Server! Found at: " + server1_location;
}
}
onlyInfo is a RichTextBox used as a dummy output atm, might stay in the final version to show what the saved batchfiles look like.
Yes, so basically my code does nothing when I click the button.
And another Question, how do I set the "*" properly for this type of usage.
Thanks in advance!
File.Exists does not support wild characters in the file name. And neither does File.ReadAllText.
string[] files = System.IO.Directory.GetFiles(#"C:\Users\" + system_user +
#"\Desktop\savedServers\", "*1.txt");
if (files.Length > 0)
{
string server1_location = File.ReadAllText(files[0]);
...
}
When I build a Windows Forms project in VS2010 in debug mode (F5) a window appears titled Output Window. There are buttons along the top of the Output Window: "Find Message in Code", "Next Message", and "Previous Message". However, they are always grayed-out (disabled). How do these become enabled?
I'm expecting the intent of these buttons is to help me find lines of code that caused a message to appear in the Output Window. For example, if I write Trace.WriteLine("MyMessage"); in client code, when executed it will make 'MyMessage' appear in the Output Window; I thought by selecting a message in the Output Window and clicking "Find message in Code" it would navigate to the line of the client code that contains "MyMessage". This would be a slick feature if it were enabled and my presumptions were correct. Unfortunately I can't get the buttons to enable.
To answer this question please explain how to enable and use these buttons and if any best practices should be applied (optional).
Here is some source code to use as reference. Create a Windows Forms project and make the changes you see below and you can reproduce what I am attempting.
// program.cs
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace MyNamespace
{
internal static class Program
{
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
throw new ApplicationException("MyMessage");
Application.Run(new FormMain());
}
catch (ApplicationException e)
{
Trace.WriteLine(e.ToString());
}
}
}
}
JasonD's recommendation
I replaced
Trace.WriteLine(e.ToString());
with
Trace.WriteLine("Program.cs" + "(" + 23 + ")" + " Some info");
End JasonD solution - result: buttons enabled
That solved it. And what an unexpected answer. In this era of strongly typed everything the answer depends on formatting strings with magic messages. I'm surprised by this.
You need to output something it can parse, which is essentially the same format as error/warning messages you see when compiling, consisting of "FILENAME(LINE) stuff".
In C#, something like this:
string file_= new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName();
int line_= new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber();
System.Diagnostics.Trace.WriteLine(file_+ "(" + line_.ToString() + ") Some info");
(this is a little messy, but there's no good equivalent of C/C++'s __FILE__ and __LINE__ macros that I've found)
You can tidy that up a bit and wrap it in a function, but you need to get the file/line of the caller, not the actual function itself:
static void traceFunc(string msg)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
string file = trace.GetFrame(1).GetFileName();
int line = trace.GetFrame(1).GetFileLineNumber();
System.Diagnostics.Trace.WriteLine(file + "(" + line.ToString() + ") " + msg);
}
I am trying to a simple C# program that takes input and passes it as output. For instance, the output should be:
What is your name?
{user input}
Your name is {user input}
The program is:
public static void Main(string[] args)
{
Console.WriteLine("What is your name?");
string name = Console.ReadLine();
Console.WriteLine("Your name is: " + name);
Console.ReadKey();
}
This is enclosed in a class called 'MainClass'
Its output is:
What is your name?
Your name is:
Why is this not working and how can I make it work?
P.S. I am using MonoDevelop and I added Console.ReadKey(); after the last WriteLine. No change.
You are trying to type in the Application Output window in MonoDevelop and it is read-only.
You can configure MonoDevelop to automatically run the program at the command prompt by right clicking on the "options" menu item of your project and checking Run on external console under the Run > General tree.
alt text http://psf.biz/public/monodevelop_run_on_external_console.jpg
I guess the guy that gave me the -1 was blinded by that huge "Works on My Machine" emblem, nevertheless this is the correct and only answer.
(source: typepad.com)
Is your problem that the program quits immediately after reading the console input? If so, then add a Console.ReadKey(); after the last WriteLine so the program will wait for a keypress. Otherwise, I don't know what the problem is; I copy+pasted the code and it worked.