C
C#2y ago
badb0nny

❔ Reading data from a text file

I have only just started trying to work with txt files and was wondering if anyone could help me and try to fix my code! string fileName = "Cookies.txt"; TextWriter textFileWrite = new StreamWriter(fileName); TextReader textFileRead = new StreamReader(fileName); string data; if ((data = textFileRead.ReadLine().Skip(1).Take(1).First().ToString()) == null) { Console.WriteLine("Would you like to save 'dark' or 'light' theme..."); string choice = Console.ReadLine(); textFileWrite.WriteLine(choice); } if ((data = textFileRead.ReadLine().Skip(1).Take(1).First().ToString()) != null) { Console.WriteLine("You selected: " + data); Console.WriteLine("Would you like to save 'dark' or 'light' theme..."); string choice = Console.ReadLine(); textFileWrite.WriteLine(choice); } textFileRead.Close(); textFileWrite.Close();
5 Replies
Aaron
Aaron2y ago
what exactly are you trying to do
badb0nny
badb0nny2y ago
its a school assignment im basically trying to write settings to a txt file and then output them if they are present but if there isnt already a saved setting you can set one
MasterSubarashii
since this is a school assignment i won't do much but, first you need to check if the file path exists second if the file exists read inside and check if inside is null (you probably did that) third if the file does not exists, create one fourth write to the file, but you still need to check if the user's input is other than you want (other than dark or light) your code would work goodly if it is inputted correctly and don't forget to take the latest text that user has put inside your file if you don't you'll get all of the data inside that file
Anton
Anton2y ago
it's better to make an abstraction in form of a class for the settings, and then a method that read them all from a file and a method that writes them all back. then you wouldn't have that cryptic code, and you can use a well known format like json or xml or yaml to bring some more order storing key value pairs in a custom format is also fine tho
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts