I am trying to create an ai. I have got it to write a topic with information to a text file but cant get it to read. this is what i have so far. Any ideas on why it isnt working?
string information = "blank";
Console.WriteLine("Hello my name is Lou-C.");
Console.WriteLine("What is yours?");
string name = Console.ReadLine();
Console.WriteLine("Hello {0}, What do you want to talk about?", name);
string topic = Console.ReadLine();
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\simon.light\Documents\Visual Studio 2013\Projects\Lou-c\Lou-c\information.txt");
if (lines.Contains("beat"))
{
Console.WriteLine("Aaahh, {0}, I have heard of this before");
Console.WriteLine("Tell me what you know about this");
information = Console.ReadLine();
}
else
{
Console.WriteLine("{0}? I don't think i have come across this before.", topic);
Console.WriteLine("Tell me about it");
information = Console.ReadLine();
}
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\simon.light\Documents\Visual Studio 2013\Projects\Lou-c\Lou-c\information.txt", true))
{
file.WriteLine("${0} - %{1} - by {2}", topic, information, name);
}
To check for any line that contains "beat"
if (lines.Any(s => s.Contains("beat")))
However, if you used ReadAllText then your contains would work!
string text = System.IO.File.ReadAllText(...);
if (text.Contains("beat"))
Related
I am currently working on a project that is creating a rapid translating program to mess up text using google's API. But I keep running into warning CS0168 and don't know how to fix it. The code is here:
using System;
using Google.Cloud.Translation.V2;
namespace Program
{
public partial class Translate
{
[STAThread]
private static void Main()
{
Console.WriteLine("Write text to become cursed");
string Phrase = Console.ReadLine();
string TranslateText() //this variable is the problem
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: Phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
Phrase = response.TranslatedText;
//end of reapeat
return response.TranslatedText;
}
}
}
}
Even if I ignore the warning the program wont run.
There are two main problems with your code:
As others have indicated, you declared a local function but you never used it.
The application exits right away because it's done all its work. You need to add Console.ReadLine(); or Console.ReadKey(); at the end to prevent it from closing.
Try something like this:
static void Main(string[] args)
{
Console.WriteLine("Write text to become cursed");
string Phrase = Console.ReadLine();
string TranslateText()
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: Phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
Phrase = response.TranslatedText;
//end of reapeat
return response.TranslatedText;
}
string translatedText = TranslateText();
Console.WriteLine("The translated text is: " + translatedText);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
With that being said, a local function might not be the best way to handle this. Instead, you could move it outside the Main and add a string parameter to it so that you can pass the phrase as an argument to it. In this case, your code would look something like this:
static void Main(string[] args)
{
Console.WriteLine("Write text to become cursed");
string phrase = Console.ReadLine();
string translatedText = TranslateText(phrase);
Console.WriteLine("The translated text is: " + translatedText);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static string TranslateText(string phrase)
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
//end of reapeat
return response.TranslatedText;
}
Console.WriteLine("What name would you like to be known as?");
string usernameforscore = Console.ReadLine();
string path = *filepath*;
File.WriteAllText(path, (usernameforscore + " " + classicscore + Environment.NewLine));
So this code is part of a game I'm making for a project, at the end of the game when you fail, I want it to save both a person's chosen username and their score (a variable saved somewhere else). I have got it to save the two to the file, however each time someone enters a new set of data, the file is overridden and only the new data is displayed.
I would like it to write a line with the name and score, then next time the code is run, it will display the new name and score on the next line, creating a high score list.
I'm using visual studio with a console program on C#
Apologies if this is a duplicate, couldn't seem to find a fix myself.
There is a method AppendAllText() rather than WriteAllText(), as below:
File.AppendAllText(#"c:\Path\filename.txt", "the text to append" + Environment.NewLine);
You can use the below method UpdateTextFile to save data to a text file.
public static void UpdateTextFile(string fileName, string content, bool doNotOverwrite = true, bool writeNewLine = true)
{
StreamWriter file = null;
using (file = new System.IO.StreamWriter(#"D:\" + fileName + ".txt", doNotOverwrite))
{
if (writeNewLine)
{
file.WriteLine(content);
}
else
file.Write(content);
file.Close();
}
}
Example of calling the method:
UpdateTextFile("FileName", "file-content", true, false);
Hope it helps.
I'm trying to set up a simple command for entering all callers into a .txt file, everything is working out nicely except for the part where I want to loop through the list and check that no one is trying to enter more than once, it's not causing any problems to the application itself but it's not doing what it's supposed to do.
Any help would be much appreciated.
string filePath = Secret.Secrets.fileDestination;
var username = msg.Author.Username;
//ulong
var ID = msg.Author.Id;
string IDout = ID.ToString();
List<string> entries = File.ReadAllLines(filePath).ToList();
if(entries.Contains(IDout))
{
await msg.Channel.SendMessageAsync($"{msg.Author.Mention}, you have already been entered.");
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"Denied entry for {msg.Author.Mention}");
return;
}
entries.Add($"{username}, {ID}");
File.WriteAllLines(filePath, entries);
await msg.Channel.SendMessageAsync($"{msg.Author.Mention} has been entered!");
I'm trying to do something basic, read a UTF-8 encoded text file and display it to the console. Everytime I run the script my output is the following:
The file i'm trying to read is here: https://www.gutenberg.org/cache/epub/49724/pg49724.txt
I have no idea why I'm getting this output. I'm sure its something incredibly stupid that I'm overlooking but I've dumbed my code down to the following to try and identify the problem.
static void Main(string[] args)
{
DateTime end;
DateTime start = DateTime.Now;
Console.WriteLine("### Overall Start Time: " + start.ToLongTimeString());
Console.WriteLine();
ReadFile();
end = DateTime.Now;
Console.WriteLine();
Console.WriteLine("### Overall End Time: " + end.ToLongTimeString());
Console.WriteLine("### Overall Run Time: " + (end - start));
Console.WriteLine();
Console.WriteLine("Hit Enter to Exit");
Console.ReadLine();
}
static void ReadFile() {
string fileName = "snow-white.txt";
try
{
foreach (string line in File.ReadLines(fileName, Encoding.UTF8))
{
Console.WriteLine("-- {0}", line);
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
}
Any help would be greatly appreciated.
Thanks,
As EZI pointed out, check the contents of the file that gets published to the bin\debug directory and verify that the file was published in the right format.
My problem was that the file's contents was NOT being published correctly. I needed to make sure the file looks the same by going straight to the source.
not my finest moment : )
Ok, well i'm basically trying to find a certain line withing "Users.txt"
Heres my code so far.
if (ok == "b" || ok == "B")
{
using (StreamWriter w = File.AppendText("Users.txt"))
{
//Test
Out.WriteLine("Please state the username");
string user = Console.ReadLine();
Out.WriteLine("Checking..");
if (w.Equals(user))
{
Out.WriteLine("Username is taken");
}
Thread.Sleep(pause);
Out.WriteLine("Please state the password for the user");
string pass = Console.ReadLine();
Logger(user, pass, w);
// Close the writer and underlying file.
w.Close();
Out.WriteLine("Checking..");
Out.WriteBlank();
Thread.Sleep(pause);
Out.WriteLine("Anything else Mr." + Environment.UserName + " ?");
}
string choice = Console.ReadLine();
if (choice == "no")
{
Boot();
}
if (choice == "yes")
{
Console.Clear();
Console.Title = "Administrator Panel";
Panel();
}
}
want it to see if the "user" is taken, then stop them from executing the process.
Thanks for the help.
Try reading (StreamReader with File.Open) each existing username into an array/List and then comparing user input against that list.
Your current code doesn't actually read anything since you're using a StreamWriter with File.AppendText which just lets you write to the end of a file.
Examples:
Reading File into a List
List<string> users = new List<string>();
using (StreamReader r = new StreamReader("Users.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
users.Add(line);
}
}
...
string user = Console.ReadLine();
Out.WriteLine("Checking..");
if (users.Contains(user))
{
Out.WriteLine("Username is taken");
}
There are various problems with your code. Let's see if we can break it down one piece at a time.
using (StreamWriter w = File.AppendText("Users.txt"))
This code would be useful if you wanted to open "Users.txt" and append text to it. Since you want to open a file and read from it, you need to use a different object, the StreamReader object:
using (StreamReader r = File.Open("Users.txt"))
Next, you want to check if the given Username is in the file. You're doing:
if (w.Equals(user))
{
Out.WriteLine("Username is taken");
}
This isn't going to work. You are comparing a StreamWriter object with a String object. They will never be equal.
What you need to do instead is change the order of your program like this:
First, read the entire contents of the file into memory. Then, outside of the Using statement, process your user input and your username/password checking.
Let's assume the file is organized like this:
username,password
username2,password2
johnsmith,mysecretcode
janedoe,blahblah
You could, for example, read each line into a Dictionary object, where the Key is the username and the Value is the password.
Dictionary<String, String> myDictionary = new Dictionary<String, String>
// Example of adding ONE username/password to the dictionary
myDictionary.Add("username", "password");
Then, checking for the username would be as simple as
bool containsUsername = myDictionary.ContainsKey(username);
And checking the password would be:
bool doesPasswordMatch = myDictionary[username] == givenPassword;
Give it a shot! C# is a great language to learn.