❔ Using text file to add data into a list
Hello, I would like to use text file to add data from a text file that are saved in a text document.
229 Replies
i believe in you
Perhaps start with googling "C# read data from text file"?
Hey guys, great to see you again as always.
Well! I have watched tutorials and read this docs on this concept.
Read from and write to a text file by Visual C# - C#
This article describes how to read from and write to a text file by using Visual C#. This article also provides some sample steps to explain related information.
The following requirements apply to your program:
The program must be built with Windows forms. There should be a text box that shows a random book's ToString override and a button that generates a new book hint. The text box must inform the user about the title, author/publisher and type of book.
I mean I have created a list, but the first small step would be is passing the path of the file.
Right guys?
passing the path of the file to what?
Sorry, I have created this thread but didn't continue yesterday with it, but now I will stick to it.
Hello Pob are you available man?
partially
Aha!
Are you helping others currently?
What 😃
Cool man
You are free in your time and I can't scratch my head because of my dame course assignments
I can't mountain bike, I can't visit friends I can't do nothing.
Hey, noone forced you to do a C# course lol
noone what's that?
no one
My passion of becoming a developer made me apply for this course lol
so, whats the problem now?
how far did you get on reading from a text file
Well! I have read the docs, watched YT tutorials, did some search on Google. But every time I implement, I get dame errors.
This dame reading & writing seems very easy, but I don't know why I suck though.
Cmon faraj, you've been doing C# for almost a year now.
Surely you can recognize when you have made a spelling error in a variable name by now?
I know you're gonna say that, because you've told me this like 100 times and Patrik 100 so the total is 200 times 😂
Let me show you where I got this code from and it's dame working
let me stop you right there
just fix the spelling error
Look bro on your self https://www.dotnetperls.com/streamreader
C# StreamReader Examples - Dot Net Perls
Read text files with StreamReader inside a using-statement. Use ReadLine and while-loops.
Faraj!
What
The
Hell
Do you understand what a SPELLING ERROR is?
Stupid me
S
Do you like, not read the error messages that VS is telling you?
I dont understand your process at all
you seem to just type out some random code from a website and then give up when it doesnt work
How the hell I didn't notice that and I've looked many times and compared any spelling error <:picard_facepalm:616692703685509130>
Here is how it should have gone
1. Get the error message above.
2. "Wait a minute, I declare that variable just two lines above!"
3. "Oh shit, I used lowercase instead of uppercase, silly me"
4. Fixed.
I mean, I don't like to copy & paste code from random sites my friend unless I review the code and understand it first, otherwise this is considered very useless practice.
I never said you should copy paste
but I do wonder if you read the error messages that VS gives you
this is far from the first time you get stuck on a super basic error
Well! I didn't pay attention on this part where the error could be a spelling one honestly.
Yeah! You're right. This is like very very beginner stuff.
Read the error message! What does it say?
I will dabble check any spelling errors next time I promise you
The name 'identifier' does not exist in the current context
and what does that mean, in your own words?
I mean it's very obvious
like, pretend Im brand new to C#
explain what that error message means to me
That the variable shown in the error message is different than the one is already declared
no
it just means "there is no variable (or other thing) in the current scope with that name"
when you see this error message, you stop and think. What am I trying to access? Is that thing in scope? Did I type the right thing?
I mean the the capital S is different than the small s
yes, but thats not what that error message means
it didnt say "typo in name identifier, expected 'S' found 's'"
because the compiler doesnt know what you are trying to do
No
it just knows you tried to access a variable that doesnt exist
Ok
Yeah! That's about it.
Thank goodness it's solved now
The code in the image seems confusing to me
why
why are they passing parameters in the ctor
Encoding.Default, false
?Ok Faraj, quizz time
Can a class have more than one constructor?
I love quizzes
Of course why not
quizz over, you passed
yes, classes can have multiple constructors.
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-7.0#constructors
as we can see here, StreamReader has one that takes... a string, an encoding and a boolean
I mean you get one default ctor the first time you create a class and then you could define second one too depending on what you're trying to do.
Ok! I saw it here in the docs too, why would I need to pass these params Encoding & a boolean?
How about you read that documentation
maybe that would answer your question
Ok! I will definitely do.
I got an idea about Encoding but still need to know the boolean papr
I mean it says this but still it's not so clear to me
OMG there's a ton of information for each dame concept and it takes too much time to read read read and etc.. 🙆🏻♂️
then skip that part for now
skip the encoding and the bool, they are after all "optional", in that there is a constructor that doesnt use them
Ok! Yeah! I don't need to complicate stuff.
I need to write the text file, but I wanna do it in a different way, instead of the foreach loop
.
Figure out a format
What do you think wise man 😁 ?
?
I have no idea what you are asking
Really 😆
I mean the foreach loop, and the code underneath? Is there aanother alternative?
??
you make no sense
Are you trying to read or write? What have you tried? Where are you stuck?
.
I'm reading data from text file
Sorry, I might asked the wrong question.
then why the hell are you saying "I need to write the text file"
Hahahaha sorry, it was just missunderstanding that's all.
I have done the point one and two. Now I need to implement the third one
Importerade texter ska sparas bla bla bla
@pobiega
Post your code then
Ok! Gladly.
There is a lot of weird going on here
this is not a valid method signature
you create a blank novel, then add the string? why bother creating
novel
then? Also, I'm not sure if is string item
will handle EOF correctly.
so we turn the entire file into a list of strings (why not just use File.ReadAllLines
in that case?) only to then later "process" the strings by splitting them and... doing absolutely nothing with the result.Ok! I was told by another dev to define that method to use it with book objects, but then I didn't continue using it.
It's spoused to be `
Ok! I was told by another dev to define that method to use it with book objects, but then I didn't continue using it.
It's spoused to be
Could you show me an example on what you mentioned?
First hit on google....
File.ReadAllLines Method (System.IO)
Opens a text file, reads all lines of the file into a string array, and then closes the file.
First hit on google....
Ok
I'm done now with the reading
string[] array = File.ReadAllLines(path)
right?Yup
Awesome
But how do I go and do separator thing the "delimiter" like
, ; #
?thats unrelated to reading from a text file
but you would probably use
string.Split
Oh! Sorry, I asked the wrong question.
You're right. This thing comes in the book type instantiation.
Where we should split these
I mean when I add these lines to a list after reading them, they should be separated by # symbol, right?
in this tutorial the guy is passing a variable that stores the file, in my case what should I be passing? https://www.youtube.com/watch?v=cST5TT3OFyg&t=435s
IAmTimCorey
YouTube
C# Data Access: Text Files
To sign up for announcements about new videos and exclusive discounts, fill out this form: https://signup.iamtimcorey.com/ (your email will be kept safe and you will not be spammed).
Data access in C# is not really hard, but there is a lot of conflicting information out there. This video will help you clear up how to read from and write to a te...
.
Here are some questions for you to answer.
What does that file represent?
What does each row/line of that file represent?
What separates a field from another?
What does the first, second, third and fourth "fields" per line represent?
Great questions. I think we need to get deep inside the file, so I understand what's going on.
You should be able to answer all of them within seconds.
the file is consisted of some lines of data that can be read and imported by the StreamReader object
Each line represent some fields with different data types
Incorrect.
Incorrect.
They are separated by delimiter like # ; , and etc..
wrong.
I mean they're not actual feilds like we have in c# because they're only texts, but the represent fields.
Answering the last question, they represent fields.
no
What I got F grade for all my answers 😆
You're thinking of this entirely wrong.
What does that file represent?
Really
What does it REPRESENT
what ideas or information does this file contain?
explain the purpose of this file
not that it IS a file that can be read by StreamReader, thats true for every single file ever
I remember you used text file in one of the projects that I was building, you told me text file is instead of taking user input by
Console.WriteLine();
I mean it's only data that's itYES
Its a file full of data, in this case books
ok next question
What does each row/line of that file represent?
ChatGPT
Did I ask "what does a text generator know about the concept of text files?"
No, you asked what does a file represent?
no I didnt
I asked "What does THIS file represent?"
Yeah! This is what I meant too.
Ok
A title, author, type and availability of a book.
more like "a book"
but okay
Yes my friend
It's pretty clear from the names representation
ok, now...
What separates a field from another?if each row represents a book, what separates the different "fields"?
hhhmm
how is this a "hhhmmm" question? Use your eyes
look at the file content
I told you before delimiter and you said incorrect
###
Correct!
previously you said "# , . etc"
all of those are wrong
the only delimiter you have here is
###
Really
Yeah! In my case. But we should be able to use a different symbols too.
like ; , .
????????????????
Did I ask "what are common delimiters?"
does the text file accepts only ###
Nope
THIS PARTICULAR TEXT FILE uses
###
and ONLY thatI'm just giving my opinion
And I didn't ask for it
and its not relevant here
Of course
I wanted you to look at the file and go "ah, this file uses
###
as the delimiter"You're right only ### and nothing else
because that information is VERY important to solving this "problem"
if other files use
,
or not is 100% irrelevantOMG
Now, I see where you going with this.
Really.
Yeah diffentely correct
So when I asked you about the delimiter, you told me that's unrelated to reading
Any more questions?
What does the first, second, third and fourth "fields" per line represent?
First is book title, author, type and availability.
They represent fields
Right?
You seem like you're playing a game
I am
Yes, they are indeed title author category and .. something else, availability sounds good
so now that we know all this, and we know how to read a file into a
string[]
what do we do next?Awesome man. I really miss playing games, I did it a lot when I was younger. What console do you have and what game?
I mostly play on PC
currently Diablo 4.
Really not ps 5 or Xbox
Ok! Swedish kids talk about some game called Fortnite all the time or Minecraft.
yup, they did 10 years ago and they still are 😄
and those are kids games, so makes sense
Good question, I like the way you review things accurately and follow by steps, then it seems much clear and easier to see the flow.
Let me see
thats literally what programmers do :p
Ok
I need to sleep we can contiue tomorow
Back on track
Progress?
Yeah! But after my VS were closed and the project wasn't saved of me, so I think I lost it.
Now, I've created a new one with almost the same implementation.
I reached this step so far
okay
its... a bit convoluted, but it seems okay
looks like you stopped half way thou
also, why a messagebox on the bool conversion? 😄
That's a good question
Since, I'm new to Winforms. How do I validate the conversion of the TryParse method then?
Like what should I be using instead?
been reading this form and most of your questions the answer is on google
what do you mean?
why should you use anything at all?
I'd just use
bool.Parse
tbh
not even tryparse. if the value is invalid, throwing an exception is fine
because that means the file cant be trusted
And to be honest, Faraj, at this point.... you gotta start thinking for yourself
its been a year, and your problem solving skills are still very underdeveloped
it takes you several days, WITH HELP, to reach a point a beginner should be able to reach in an hour or twofirst to make this requirement you have to create a class called book first, did you create it?
But it takes a good coding skills to find solution bro it's not that easy.
Well! I could've used only
Parse
and it can throw an exception where TryParse
doesn't throw an exception but returns a boolean value. I try to use TryParse so often mostly for practicing purposes.its not that simple
sometimes its correct to throw the exception, sometimes its not
when parsing user input, tryparse is most often correct
when reading from a file the user shouldnt be editing by hand, I think its correct to throw
but parsing the bool is a trivial part of this problem
its not the thing you should be focusing on
I know and we have discussed this in the chat server too. But just like said it could be a good practice to validate imperfect data.
perhaps worry about that later
you still need to actually solve the main problem
I totally agree with you on this and I'm doing all I can and that's it. It's a hard skill and I know many people here in the server they struggle and have having a hard time with practicing it's not only me.
Thank you for showing up here in the thread bro. I have created the class + sub-classes.
what sub classes?
Of course you are not alone, but you do struggle more than most others. This leads me to believe that your current approach to learning might not be correct.
If you have classes, why are we not seeing them in your code above?
Man, I told the others about this too but they were constantly saying no you need to expect that the data can be imperfect. I think you're about that.
To be fair, you seem to be asking for help in like 4 different places, giving different context in each.
but in this case, its not user provided data
you are not validating the strings at all, so why the bool?
This is my problem. I waste day and night only for a small stupid issue where I could use that time to practice more relevant stuff. I need to start a new strategy.
In my opinion, you are focusing too much on code, and not enough on problemsolving
You need to actively practice and work on your ability to break down a problem into smaller tasks
Let me show you
for example this one, there is so muhc more than just reading from a file going on
there is turning a string into a an instance of a class, there is the GUI elements, there is the the actual file reading, which can be done in a multitude of ways
Is there a requirement to have subclasses for Novel etc?
LISTEN TO US
Yeah! My problem is I set and think generally about the whole program and not splitting into small steps and this lead to waste at least 5 days with confusion. I'm sooo tired of this learning method.
I just showed them
Yeah! This is very wrong too. It causes even more confusion, because everyone has a different approach.
yeah but where is your
var book = new Book(...)
in the code above then?
you've MADE classes, but you dont use themYes, just take a look at line 3 in the requirements.
besides its asking you to save as books, of the correct subclass
ah I see.
you have missed several of these btw
for example, your file reading code should be in its own class
Well! This is where I needed to know how to implement that on line 3.
i think its time to stop writing code and start thinking
you need to plan your stuff more
Aha! Which class?
Read your requirements. Line 2 i believe.
Yeah! I think this is definitely what I should be doing.
Ok
It says I should be adding a class + import the date + save as books is this easy to do?
yes
Save the data as books in a list
Well! For you not for me bro.
It's easy for you because you have done it before so many times and I have not done this before.
to some extent of course, but at the same time, you have the code for all of this already
you just need to re arrange it a bit, and make some methods
Ok
tell you what, here is your once in a lifetime offer. lets jump on screenshare and ill teach you how to break the problem down.
Ill give you 45 minutes at most.
See this is where I get stuck and try to find a way on how to do that.
Awesome man. Thank you sooo much.
wrong channel
#dev-vc-1 @Faraj
...
doomed
How does it take 5+ minutes to notice you are in the wrong channel, when I have even pinged you? O_O
@Faraj it's better if you post any additional questions that you have here so people can help you
in chat you have the chance that people won't look at them
Thanks a lot buddy. You're right. I don't ask in the chat anymore, there are some people confuse me with many different opinions and some come to me and say "You've been in c# for a year" why you haven't learned the fundamentals, they act like they're Bill GATES or Steve Jobs and if you ask them about their education background, they all spent at least a year in the fundamentals in computer science uni.
yes, that's certainly hurtful especially when you're trying hard to try to learn, but it's also important to plan and chop up your learning path into smaller pieces before moving on to doing too much
if you're overwhelmed with the material to learn, it's good to start from the very basics and make sure you really understand those, and feel comfortable with them, before moving on to something more complicated
I briefly watched Pobiega teach you and he really broke down the problem and tried to teach you how to think like a programmer, using the features that the C# language provides
I really don't care what others say. But I don't wanna bother ask them for coding questions either.
that's perfectly fine, you should learn because you want to learn and not to please others, but please understand that having a learning strategy is also important
and that you don't dive in head-first
Yeah! You're absolutely right. He is really good and giving the right tips and path to learn and think like a programmer. This talk changed the way that I was learning. The whole time I was taking a very wrong learning path.
so how has your learning strategy changed, can you summarise what you're trying to do now?
Yes, that's really good question.
The first thing I do is split each problem into small steps where I think clearly and figure out what I'm doing and why?
I read my code step by step and I Google for solution and read the docs and the most important thing is I test code not just read read read the docs.
I try to think about every tiny concept in code, why this? How to do this? What can I do with this?
those are very useful things to do
Are you from Eu or US btw?
I'm from EU
Wow, awesome. I'm from Sweden.
I'm from Belgium
Great. I hear sometimes from Belgium it's a nice country and not as cold as here 😆
(and they make good beer)
Are you a developer like senior, because I feel like you have a good enough experience from what you usually write.
hahahaha really
no lol I'm very much still a junior
I like programming but I focus too much on .NET and I don't take enough time to learn about other technologies that work with .NET (such as HTML and CSS for making websites, for example)
I have never touched a girl in whole my entire life and never drink anything except for coca cola and never smoked either because I'm muslim.
obviously I can't force you to try our beers but even though I'm biased I must say we make good beer
there's plenty of bad beers here too but most are good
Really! I'm impressed. I like to ask you this because you're the one. How long experience do you have in .NET? What does it take to be a junior dev, because this is my goal.
Ok! I know nothing about beers, because I never drink anything like that. I love sport and this makes me happy healthy and grateful always.
the Belgian government provides training to get you ready for certain jobs, and I did the training for .NET development for about 9 months before I started at my first job
my first job went pretty bad because I was too inexperienced but the next job I got I had a great senior dev who taught me many things
and in total I've been programming for about 3 years now, but I still have lots to learn
Ok! So you had 9 months and you felt inexperienced.
Wow, what a luck. Thanks to him you're living your dream of becoming a junior where people struggle to get this position.
absolutely, a good mentor makes a huge difference
so it's good that you ask questions in this discord server because there are so many people with so much experience that can point you in the right direction
Man every successful programmer or business owner talks about getting a mentor, it's very stupid and wasting time to ignore or be greedy to pay for a mentor where you could save sooo much time, confusion and headacke.
Like Pobgia, Klarth, thinker and Merit they're really good and very very very supportive developers.
I think this guy Tim Corey looks a good teacher too and he offers courses on his website like this one I'm thinking about to purchase https://www.iamtimcorey.com/courses/csharp-mastercourse/
C# Mastercourse - IAmTimCorey
Master C# from the ground up. Get real-world ready by the time you complete this mastercourse.
actually, have you done $helloworld before?
Written interactive course https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/
Videos https://dotnet.microsoft.com/learn/videos
you should drink water often 😄
drinking coca cola only doesnt sound healthy
Not really sure if I will benefit or become a junior dev after finishing the course as he claims, but maybe worth to try. Although I see no reviews either.
don't worry about what it means to be a junior or senior dev, worry about learning and retaining more knowledge than yesterday
or last week
or last month
Well! I used to drink coca cola. but since it contains too much dame caffeine, so I gave up this for a long time ago. Caffeine in coca cola effects my brain, I can't sleep and the next day I end up with too much brain fog and I look stupid when coding later.
TheRanger is right, water is healthier, but if you want something more flavorful you can always drink tea as well
i drink coffee at morning
at night is bad, will keep me awake
Exactly, today I regret of my bad mistakes and my learning path which I wasted a lot of time following a wrong path of learning coding, but following the Pobgia tips will save me a lot of time in the coming assignments and projects.
You're right. According to the sleep expert, you should drink coffee 14 hours before you sleep. That means not after 10 o'clock, because out brain contains some amount caffiene.
Dr Rangan Chatterjee
YouTube
Sleep Expert REVEALS How Caffeine DESTROYS Your Sleep & Productivit...
Today’s guest is world-leading sleep researcher, author of the international best-selling book ‘Why We Sleep’ and Professor of Neuroscience and Psychology, Matthew Walker.
Matthew shares research on the effects of caffeine on our sleep.
Caffeine is a sleep disruptor, and just one dose of caffeine in the evening can decrease the amount of deep ...
Check out this video
For becoming a developer, I do the following every dame day. I never drink coffee later than 10, I never eat or drink sugary products, I train every morning at 5:30, I do meditation every morning, I go to bed before 10 o'clock. I take could shower two times everyday. I set on the computer everyday for many many hours and lastly I do physical activities like football, floor-ball, hide and seek games with the kids and bicycle every weekend.
😁 isn't that funny
I always thought why I'm doing all this and not getting forward in coding then I realized my learning method was wrong, so it's not the health issue.
it seems like you're a very busy man, so I imagine it's hard to find the time to learn
No, man. I'm a single and I study a course on 100 percent rate and work 100 percent and I do the activities when I'm finish with learning and during the weekend.
Are you expected to know all these as a junior like OOP Linq Interface UI Delegate and a framework like .NET Maui? Do you know all that?
OOP, Linq, interface, delegates.. yes.
MAUI, no.
ASP.NET, probably yes but varies based on job
Ok! I thought so too. Basically, a junior dev needs to know the following above in order to help the company when building apps or websites, right?
Those things you've mentioned are quite abstract and you will need to understand the fundamentals of a programming language before you can try to apply those abstract principles
But yes, they're very widely used by programmers of any level of expertise
Ok! Yeah! I should learn and practice all these before jumping into any career or something. Although they're not easy.
You will need to know these to have a chance at landing a job, most likely.
Yeah! I will do whatever whatever whatever it takes to reach this goal.
I think investing on a good courses would help me to reach this goal. Learning by my self it's very boring way to learn.
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.