0:00 - Intro 0:54 - Creating Demo Console App 1:39 - File path: string literal explained 2:51 - Reading from text file 5:00 - Writing to text file 7:07 - Populate DataModel fields form text file: 9:33 - • Line split 12:20 - • String interpolation 15:24 - Note on data validation when reading form text file 17:45 - Adding object to a list: 18:47 - • Anonymous instance explained 19:45 - List of DataModel to text file 23:22 - Summary and concluding remarks
Thank you so much. The professor I have never makes us code, He always give us a power point presentation and send us home with a lab. It is nice to see someone who takes the time and explain us the code behind the theory.
Can't belive it! 80% of my work is based on text files, move it, make logs about the actions taken, update, read it to valid them, awesome Tim, you get a great way to teach. I am your Fan!! Its pure gold. Thanks so much!
EXTREMELY helpful. I have been seating at my laptop for 3 hours trying to find how to read and write from text files to make a log-in interface and nothing helped me, except this beauty. Much appreciated!
I can't believe how helpful this actually was. I'm actually mind blown by how you managed to convey so much information and clear up a lot of my question so simply. thank you very very much. You're a blessing to humankind
Amazing! Informative, clear and useful information! Please continue to make these great videos, I appreciate them and thank you for your time in making them!
Reading from and writing to text files has come in very handy to me. Thank you, Tim! :) I've been doing access and security system upgrade at work for a client. Database form old system was not compatible with the new system, although it was the same manufacturer... So only option was to re-configure whole system by hand. Lucky for me, old system had a feature to print out programming as csv files. And new system could take csv in. Only problem was that text files needed to be cleaned up and needed some other work and many manipulations to be usable. Now with C# I've been flying through text files containing thousands of lines like it was nothing. Filtering, rearranging, creating new lists and other stuff. New system was ready in no time. So to speak... These basic techniques has really made my life easier. To give you some kind of reference - we don't use computer programming at work. We work with hardware. Installation and service. Electronics. To use C# at work is like using some kind of space age technology. Very exciting! One may argue, that you could use excel for working with csv... I'd say - excel is limited thou. You can't do stuff with excel like you can with C#. With C# it's freedom. Thank you!
I'm struggle to build a "practising app" when learn C#, don't know how to get data to excute and then save back to. Text file absolutely is easy way. Your video help me much. Hope I've learnt more from your database turorial. Thanks.
First of all thanks for refresher. Sometimes if you get lost in c# thing become really complicated than they should be. This is an old video but still so relevant. I just fixed some of my code after watching it. Your video never fail to deliver. I really appreciated your efforts. 👍
Tim, that was So well explained!!! Just learning C# in past week after VBA. Storing data is key. You’ve shown me how easy this is and also to understand what’s happening. Thank You!!!
I believe this is what Facebook used to store plain text passwords. They probably watched your video and thought, "Hey, we can save time by not hashing password in a database, it will be quick." Brilliant.
So that wasn't about passwords in a database. What happened was that they had a logging system that logged when certain actions happened (common). One of the log actions captured a user's password (I believe it was when it was changed but I can't remember exactly). That log was in plain text so the user's password was in it if you looked for it. They weren't storing the user's password in plain text. That was encrypted. Their logs, though, weren't. That's why security is more than just about a password or SSL. You have to think about every step along the way.
Thank you , your list of string method is very elegant. List processing has come of age compared to multidimensional arrays, which are fine if your a string theory physicist used to thinking in multi dimensions.
Awesome and clean explanations especially for us beginners, wish to see more tutorial on delegates, reflection, dependency injection, rest services, more in-depth on unit testing, web api and asp.net mvc
I appreciate the suggestions. Unit testing videos will be coming soon, along with dependency injection for sure. The others are coming, just further back.
Great video Timothy! You make it so easy to understand.if you can...Could you please make a video on how to validate data in a List?Like how would you check if a new Person you are trying to add is already on the List?Thank you
No matter where I place the file, and write the file path EXACTLY as i have it structured, the compiler will not find the file and runs an exception. I cant seem to find anything about how to fix this online. EDIT: Pretty sure that it was reading the file "Test.txt" as "Test.txt.txt". When i removed the ".txt" part of the file name, the program compiled normally. I found that solution on stackoverflow and it helped out. Anyways, it was a naming problem on my end. Sorry for the mix up and thanks for the tutorials :)
Wow didnt know about interpolated strings ($"") being faster than " "+"..." Etc.This i will use in the future even for convenience and perfrmance gain.Thanks!
When demoing a specific topic, I try to stick to that topic specifically. Otherwise it can become overwhelming to the viewer and confusing as to what is "other code" and what is code specific to the topic. I'll be doing a video specifically about error handling in the near future though.
I am a relatively new programmer, I have an assignment where I have to take a list of "employees" (a string of numbers) and sort them out. The strings are in a 6 digit format such as 020106, where 02 is the territory, 01 is the area and 06 is the department. I then need to take them and organize them. There is a total of 69 strings and I need a way to read them from a text file, sort them and then output as shown below (in a new text file) Any idea how I would go about doing that? Example output: Terr - 01 Area - 01 Department Number of Employees 01 1 05 15 06 3 Area - 02 Department Number of Employees 06 7 Terr - 02 Area - 01 Department Number of Employees 06 1
Hey Tim, love your videos. They've really helped me get information in and out of a file. One thing I'm unsure of though, is how to do you overwrite data after variables have been changed during an apps use? Would it just be a case of clearing the file before you save your data again?
The version of the save I am using overwrites the text file instead of appending to it. You can change that, though, if you want to append instead of overwriting.
I found this tutorial pretty helpfull . In the last 3 years of me coding , i have not been able to make a High score system in the games i have worked on =)
Depending on the video, I do post the code but usually the code is small enough that you can follow along and re-create it for yourself. That has the added benefit of increasing your learning while providing you the code.
Old video but to a an old programmer updating my skills it's gold. It re-writes the file each time. Thinking of huge text files 500MB to 1GB it would probably take forever to save. Thinking of changing it to only update the changed lines, what would you recommend I research C# wise?
Things break. You have a couple options then. First, you could strip out commas before you insert the values into the text file (in case they aren't needed), you could change the delimiter (pipe is almost never used in normal typing or you could use a double character like two pipes), or you could account for it using double quotes. That last one is a bit trickier because you have to change how the split works. You would manually split the records but if you encountered a ," combination, you would not split on the next comma until after you saw the end double-quote symbol. This is how "real" csv files work.
Hi TimCorey it is very good video for beginners like me. I have a doubt where if the lines in file are of different length(15:46 time in this video), i.e more than three entries per line lets say i have four lines first line has three entry,second line has two entries the third line has five entry and fourth line has four entries. how to handle this situation..?
Well, you have invalid data then so you need to set up a rule about what happens in this case. That will depend on your application. You might ignore the row entirely, you might take the raw data and put it on the screen for the user to see in an error message, you might put that data into a textbox on a form so that the data can be modified/cleaned up, or you might do something else with it. The key is to remember that it is bad data. You cannot tell which column you are missing or which one is the extra column. Therefore, it cannot be handled automatically with confidence.
very useful. However my output file will be hundreds of lines long. Reading it in as a list, adding one line and then writing it out will take up too much time. I need to just append/add to the file by adding a new line. Any thoughts?
I have a question. If i wanted to access, for example, greg jones lastname, and change it to a new lastname, or for that matter any variable, how would i achieve that? As far as i know, list have index to access, but can i make it so, that all person also has ID variable, that is stored in the text file, and use that ID to get all the content of that particular line, and then do stuff with that line person information. Hope it makes sense.
Text files cannot be used like databases. You would need to read in the file, make the change, and then write those changes back to the file. The easiest way is to read the whole file and then overwrite the whole file with the new data.
I'm curious what you would recommend if one wanted their application to save individual files in the same manner as Excel with .xlsx, Word with .docx or Acrobat with .pdf. I believe some of these formats are simply XML documents, which is just a fancy text file, is it not? I'm currently looking at using JSON to create my "own" file format. Wondering if you have thoughts and/or suggestions for this approach. As always, thanks!
I would recommend using a tool to build those formats. You technically could create them but it would be a LOT of work. Writing to the file is the simple part. Knowing what to write is the hard part.
im a tad bit confused, when using file.WriteAllLines(FilePath, output); shouldnt it write all of the other person instances instead of just writting another greg
We do, but we are overwriting the existing file, which means the file looks like we just added another Greg, when in reality we wiped out everything, rewrote everything, and added an additional entry.
Hi Tim, Thank you for your videos. What happens when a new object is created in a for/foreach loop? Is the first object reused? If not, then on a larger scale could creating objects in for/foreach loops produce clutter in the program, and what could be done to avoid that? The first thing I think of is creating a placeholder instance of an object outside of a loop that the can be accessed, using it to hold temporary values. It also dawned on me to possibly add a number at the end of each instance being created within the loop so each instance has a unique name. Am I over thinking this? I would like to know how this is functioning on as low-level as I can.
In a foreach loop, the variable is getting re-initialized in every iteration. The old data is discarded and the garbage collector will clean it up. However, if you are iterating over objects (like class instances), you aren't actually duplicating the class, just the location of the class (super-efficient). No, there is rarely a case where you need to optimize a foreach loop because of the variable. I can't remember an instance where I've needed to do that. The placeholder wouldn't solve anything because it would end up doing the same exact work. Adding a number to the variable name? No, you couldn't do that and it wouldn't be valuable to do. In fact, it would be terribly inefficient. The variable only lives for one iteration of the loop. In your mechanism, it would actually last longer (in theory).
@@IAmTimCorey I came across the term garbage collector somewhere but I haven't really thought I should look into it until now. I appreciate you clearing up some of my speculation (though there will always be more) with your response. Thank you for your time and service. Subscribed!
First of all, Thank you VERY much for your free, comprehensive videos!! I cant say how much they have helped me. I have a question that have been researching and could not find the answer for it. I have a program that generates a text file and I want to create report based on that text file. I have found Microsoft report viewer but I am not sure how to use it with my text file. I dont want to pass the whole text file to the report viewer, rather pass some parts of it and create a table out of it in my report. I would greatly appreciate any help.
It sounds like you should create a second text file that is the one you run through report viewer so that you don't have to worry about reporting on the whole thing. As for creating a table out of the data, that's something you will have to play around with. Maybe create a CSV file and have report viewer parse it?
Thank you very much for your quick reply. Can I pass images to report viewer as well. Is there a tutorial on how to do that? Since I want to pass some images as well as the text file combined together.
Hi Tim, what if two fields in the text file are numbers and you wanted to calculate the sum of the two numbers in a new field then output that into the same text file?
Hi Tim! ReadAllLines is not useful if it is a huge file, and we probably need to read it in chunks with an open connection. Can you make a video on that?
Great video. Is this the same as serialization? It would be great if you could do a video on XML, JSON, and other types of serialization. Also, how to read and apply a configuration file. Keep up the great work!
Was the class Person declared from another file? I tried doing this code but when I typed the word Person it says "The type or namespace 'Person' could not be found"
I'm not sure I understand the question. Yes, you get to choose what you print to the console. You can print just one object or even just one part of one object to the console.
This is easy and all i knew all this stuff before the video... But how do you read a different kind of data in a separate lines e.g. when you got a text for several lines and then an array. How do you sort that kind of information because parts[0], parts[1] etc is not going to work anymore. Also how to store delimiters to a result file aswell?
Dear Tim Corey, Is there any way to insert a string into a specific row location of a .csv file? (e.g. I want to insert a string to the second row of a CSV file which has 10 rows data)
@@IAmTimCorey but my csv file is pretty big (maybe over 10.000 lines), and I just want to modify the second line of it. It's a bit risky if I change all the content of the file just to modify a single line.
Very informative video helped me out a lot, but I have a question. Is there a way to pass text from the file into a 2D array. so each comma represents a column, and line represents a row to make up a table. i.E mammals, Dogs, cats, horses, Platypus Fish, Clownfish, Salmon, Crayfish, Tuna Birds, Parrots, Pigeons, Sparrows, Penquin The point is to make an easy way to randomly choose a category and then display the elements within it.
Dear Timothy, I had to use the following syntax for displaying people using foreach loop, since my VS2010 does not support the $ format: Console.WriteLine( "{0} {1} {2}", person.FirstName, person.LastName, person.URL ); However, trying to use the same format for writing the fields back to the file as a single string confuses me: output.Add( "{0},{1},{2}", person.FirstName, person.LastName, person.URL ); This doesn't work, as Add takes one argument, and not four. output.Add("{person.FirstName},{person.LastName},{person.URL}"); This doesn't work either, as the same literal strings get written back to the file. I wonder if you could please help me figure out what to do here? Thanks
Will this work for reading .cfg files if I alter the code to look for that file instead, also would this work for Unity, since it might be using the same concept, just replace most of the logging with Debug.Log?
The code doesn't care about the file extension. If you can open it in Notepad, you can open it, modify it, and write back to it in C#. So yes, you can modify cfg files. As for Unity, not sure. I would assume so but Unity C# is a bit different than full C# (it isn't as current).
how to read a file columnwise and to print each column to new seperate files.content of the file is Ist column is time and n number of columns .All are in float.Could u please help.
Hello Sir, how much significant it is know what happens behind scenes while programming applications. Like how variables will be stored in stack ,heap.Is it necessary to know underlying details in most of applications?
It is not really necessary for the most part. The biggest thing to understand is performance basics. For example, I know that appending one string to another is an expensive operation. That is good to know so I don't do that in a loop. Otherwise, I could make my application really slow. I also know to create only the variables I need, not tons of extras that will just clog up the memory (although .NET is good about getting rid of unnecessary variables). However, I don't concern myself too much with the deep dive memory management stuff, nor do I recommend that others do so. Focus on writing good C# using best practices. Those best practices are sometimes based upon performance. You don't need to know all the details to use them. That way, you can focus on writing good applications. If you spend too much time worrying about the obscure details, you won't have as much time to write the great programs.
IAmTimCorey thank you so much for great inputs. I always like you how you explain in detail to every question we ask. You are one of awesome RUclips programming channels in the world. Thank you teacher :)
Hello Sir, I have one doubt. It might be a dumb question. Suppose we have two classes in same namespace like in the image imgur.com/a/Z8hhzKz, I cant instantiate Program class object directly inside Program2 class without writing inside some method like constructor. What is reason for this, is it that all code inside class should be inside a method? I couldn't figure out why. Thank you
Yes, all code except variable declaration and initialization needs to be inside a method. Also, you are instantiating a new Program class but you don't need to do that to call Main. Main is static so you can just say Program.Main() to call it.
Thanks for this video. I have problem here> I am using a Visual Studio 2012. When i type: Console.WriteLine($"{person.FirstName} {person.LastName}: {person.Url}"); i get error: Unenspected character '$' If i change to: Console.WriteLine(person.FirstName +""+ person.LastName+":"+person.Url); it is works. What is the problem? version VS2012 or something else ? Sorry, english is not my native language. Best regards
Yep, the issue is Visual Studio 2012. String Interpolation (using the $) was introduced in C# 6.0 (Visual Studio 2015). If you are stuck using Visual Studio 2012, you will need to either do what you figured out (which isn't very efficient so don't do it in a loop) or you could use the string.Format method (which is built right into Console.WriteLine or you can call it manually at any other point). Your line would then look like this: Console.WriteLine("{0} {1}: {2}", person.FirstName, person.LastName, person.Url); However, if you aren't restricted by your company or the age of your computer, go to www.VisualStudio.com and download Visual Studio 2017 Community Edition. It is free and it will give you all the new features available in C# 6.0 and C# 7.0 as well as all the improvements to the tooling.
Hey Tim, what's the difference between using a streamwriter/reader or just simply using File.(...) ? Both can achieve the same thing. And thanks for the videos, great help!
I'm getting System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect. error. I copy and pasted the file path name from the properties to the code and checked multiple times to make sure it's correct.
Couple of things. First, be sure there aren't single slashes unless you are using the "@" symbol in front of your string since slash is an escape character. Next, verify that the path actually exists by going to File Explorer and pasting it in (fixing the slashes if you need to).
@@IAmTimCorey Finally got it to work using: *string filepath = Path.GetFullPath(@"C:\Demo\Test.txt");* *string filepath = @"C:\Demo\Test.txt";* was not doing it at all. I'm using Visual Studio Version 16.5.0. Thanks for your response and keep up the good work. Definitely, be watching more of your videos.
@@scientist100 Tried it again without the Path.GetFullPath and now it works. Don't know what the hell was going on. I used the same path. Literally, the only thing that was different was using the Path.GetFullPath.
@@quantomic1106 glad it worked, I'm learning C# and this course appears to touch all basics of C#, I'm very familiar with VB.net and actually develop in the VBA environment but I'm thinking I should use stand alone applications for reliability and to connect multiple users at the same time. The set-up that I have is a bit weird but it becomes complex but I'm the one that knows what happens behind the scene of the application.
Let's say I want to have a Link on a GUI open that textfile. How would I designate the path so that anyone who runs the program can open it? Since the file path may not always be the same depending on where on person saves the project vs where I saved it. I keep the text file in a textfiles folder inside of my project folder.
Well, if it is a known location relative to your executable, you can use a relative path. You can also have the user find the text file the first time they use the application and you can store that information (the file path) in the app.config file (or you can do it on install).
Hello, Tim! First of all, thank you for this video, it really helped me out a lot on a project i'm working on. I have a question though. I want to be able to search for the first element in the file and have the program return the rest of the line to me. Here is an example - Die: 747 measurement: 266.7 Notes: Some sample note here. Something like this but I want to search by die, in other words, the first element. Thanks in advance. Best of luck to you.
@@IAmTimCorey Ok, thank you. I'll try that. I'm also having a really hard time using this code in a try catch block and at the same time creating the file. Any suggestions?
Hi awesome video helped me a lot already but how do i handle the problem, when i only know what my 5 first columns are and after that i can have unlimited more columns? So i know my first couple columns are name, last name, street, etc. and after that i get for every file i want to load a different amount of columns that i dont know anything about.
Not a problem. Since you read each line in as a full line and then split on the separator (usually the comma), you can have as many columns as you want. You probably cannot create class properties for each column but you can have an array property that handles all of the "extra" columns.
There is a .txt file with many variables in it, and I want to display the value itself but when I do this it displays the whole line. Any tips? Cheers.
Hey guys , in case you guys need the code . here it is linked below . The file name i have used is different so keep that in mind . hastebin.com/nomewuxeci.cs
I am not sure I understand the question. I demonstrated how to read from and write to a text file. To do it with a button click event would just require that you call those methods from the event.
Adding to a string array is difficult so you used a List Collection. But why didn't you use StringBuilder type which easily supports adding data ? Kindly answer.
A StringBuilder works if you are doing one line. I wanted to add one line per row of data. A list is the easier way of doing that. You can use the line returns in StringBuilder but it isn't as clean.
0:00 - Intro
0:54 - Creating Demo Console App
1:39 - File path: string literal explained
2:51 - Reading from text file
5:00 - Writing to text file
7:07 - Populate DataModel fields form text file:
9:33 - • Line split
12:20 - • String interpolation
15:24 - Note on data validation when reading form text file
17:45 - Adding object to a list:
18:47 - • Anonymous instance explained
19:45 - List of DataModel to text file
23:22 - Summary and concluding remarks
Thank you kind sir!
Thank you so much. The professor I have never makes us code, He always give us a power point presentation and send us home with a lab. It is nice to see someone who takes the time and explain us the code behind the theory.
Glad I could help!
Can't belive it! 80% of my work is based on text files, move it, make logs about the actions taken, update, read it to valid them, awesome Tim, you get a great way to teach. I am your Fan!! Its pure gold. Thanks so much!
I'm glad this video will be so useful to you.
EXTREMELY helpful. I have been seating at my laptop for 3 hours trying to find how to read and write from text files to make a log-in interface and nothing helped me, except this beauty. Much appreciated!
I am glad it was so helpful.
I can't believe how helpful this actually was. I'm actually mind blown by how you managed to convey so much information and clear up a lot of my question so simply. thank you very very much. You're a blessing to humankind
Glad it was helpful!
Finally a programmer with common sense who can teach! Thanks!
You are welcome.
Amazing! Informative, clear and useful information! Please continue to make these great videos, I appreciate them and thank you for your time in making them!
Reading from and writing to text files has come in very handy to me.
Thank you, Tim! :)
I've been doing access and security system upgrade at work for a client.
Database form old system was not compatible with the new system, although it was the same manufacturer...
So only option was to re-configure whole system by hand. Lucky for me, old system had a feature to print out programming as csv files.
And new system could take csv in. Only problem was that text files needed to be cleaned up and needed some other work and many manipulations to be usable.
Now with C# I've been flying through text files containing thousands of lines like it was nothing. Filtering, rearranging, creating new lists and other stuff.
New system was ready in no time. So to speak...
These basic techniques has really made my life easier. To give you some kind of reference - we don't use computer programming at work. We work with hardware.
Installation and service. Electronics.
To use C# at work is like using some kind of space age technology. Very exciting!
One may argue, that you could use excel for working with csv... I'd say - excel is limited thou. You can't do stuff with excel like you can with C#.
With C# it's freedom.
Thank you!
Thanks for the tips
I'm struggle to build a "practising app" when learn C#, don't know how to get data to excute and then save back to. Text file absolutely is easy way. Your video help me much. Hope I've learnt more from your database turorial. Thanks.
You are welcome.
Chuckles. Just keep standing on that "soapbox". The Gospel you sing is very informative and good learning! So don't give up on it, mate.
I'll keep preaching good development practices. Don't worry. :-)
First of all thanks for refresher. Sometimes if you get lost in c# thing become really complicated than they should be. This is an old video but still so relevant. I just fixed some of my code after watching it. Your video never fail to deliver. I really appreciated your efforts. 👍
You are welcome.
That is the easiest and clearest I have ever seen that explained.
Thanks.
thank you sir. I spent the whole day manipulating data with jugged arrays, I am giving lists a try.
You are welcome.
Tim, that was So well explained!!! Just learning C# in past week after VBA. Storing data is key. You’ve shown me how easy this is and also to understand what’s happening. Thank You!!!
Glad it was helpful!
I believe this is what Facebook used to store plain text passwords. They probably watched your video and thought, "Hey, we can save time by not hashing password in a database, it will be quick." Brilliant.
No, Facebook doesn't store clear-text passwords.
@@IAmTimCorey You didn't read about it? www.theverge.com/2019/3/21/18275837/facebook-plain-text-password-storage-hundreds-millions-users
So that wasn't about passwords in a database. What happened was that they had a logging system that logged when certain actions happened (common). One of the log actions captured a user's password (I believe it was when it was changed but I can't remember exactly). That log was in plain text so the user's password was in it if you looked for it. They weren't storing the user's password in plain text. That was encrypted. Their logs, though, weren't. That's why security is more than just about a password or SSL. You have to think about every step along the way.
You are a godsend, sir. I love your videos. The 18 people that thumbs downed should be ashamed of themselves.
Thank you!
Thank you alot, that was the type of tutorial that I needed
Excellent!
Like the way you explain things. You just got a new subscriber. Definetely will watch more!
Tim Great Video. New items make it far clearer.
Thanks Tim. Great tutorial, very clear and concise as with the rest of your tutorials. Keep up the good work!
You are welcome.
Thank you , your list of string method is very elegant. List processing has come of age compared to multidimensional arrays, which are fine if your a string theory physicist used to thinking in multi dimensions.
Yep, List is pretty powerful.
thx for the videos, I like that u go in-depth on one particular thing.
You are welcome.
Awesome and clean explanations especially for us beginners, wish to see more tutorial on delegates, reflection, dependency injection, rest services, more in-depth on unit testing, web api and asp.net mvc
I appreciate the suggestions. Unit testing videos will be coming soon, along with dependency injection for sure. The others are coming, just further back.
Thank you! Simple and to the point, thank you very much! I just subscribed just because of this one video.
You are most welcome. Thanks for watching.
Awesome video, very clear for a non-native english speaker.
Excellent!
Nice Video Timothy! Thanks
timothy ? :D
This was an extremely helpful tutorial! Thank you so much for posting this!
Very good, professional work.
Thank you for your effort.
Please, continue .....
Will do.
this video helped me alot, very useful, clear and simpel information. Thanks alot Tim :)
Awesome!
Thank u so much sir for making concepts this much simple and effective... i appreciate ur effort for these tutorials...
You are welcome.
So exceptionally great! Thanks for all your awesome videos! :D
You are most welcome. Thanks for watching.
One of the best tutorials ever!!
Thank you!
great one.I love the way you are explaining things.Thanks
You are welcome.
I tried to implement the method to asp.net text box.But it's not working
Thank you Tim, love your exposition
You are welcome.
Great video Timothy! You make it so easy to understand.if you can...Could you please make a video on how to validate data in a List?Like how would you check if a new Person you are trying to add is already on the List?Thank you
Wow, you really know what you're doing. Great tutorial!
Thank you!
Awesome vidio thank so much. But how do I search for specific line(person) then remove it?
Thank u so much
Excellent video, many thanks!!
You are welcome.
Damn, so its called spring interpolation now everything popped up on google, these keyword are really tricky. Thanks for the tutorial.
I am glad it was helpful.
No matter where I place the file, and write the file path EXACTLY as i have it structured, the compiler will not find the file and runs an exception. I cant seem to find anything about how to fix this online.
EDIT: Pretty sure that it was reading the file "Test.txt" as "Test.txt.txt". When i removed the ".txt" part of the file name, the program compiled normally. I found that solution on stackoverflow and it helped out. Anyways, it was a naming problem on my end. Sorry for the mix up and thanks for the tutorials :)
Glad you figured it out.
Thank you, I liked and subscribed to your channel! just what I needed to expand my knowledge
You are welcome.
Thank You Tim for all your content, please can you create a tutorial about XML Serialization and Deserialization in C#
Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/
You my sir are a life saver thanks :)
You are welcome.
Wow didnt know about interpolated strings ($"") being faster than " "+"..." Etc.This i will use in the future even for convenience and perfrmance gain.Thanks!
It is faster to type and read. Performance-wise, it is equivalent. Sorry for the confusion.
Amazing content. Thank you!
Thank you!
U R Amazing man ,thank u from Idlib and wish u be in All Fine thinks because U R Powerfull Teacher
I appreciate the kind words.
@@IAmTimCorey can u make video About sending Files to Email by C# ?
Great video. If you can add more error handling checking, it is very helpful. Thank you!
When demoing a specific topic, I try to stick to that topic specifically. Otherwise it can become overwhelming to the viewer and confusing as to what is "other code" and what is code specific to the topic. I'll be doing a video specifically about error handling in the near future though.
Great tutorial !!. Thank you so much Sr.
You are welcome!
I am a relatively new programmer, I have an assignment where I have to take a list of "employees" (a string of numbers) and sort them out. The strings are in a 6 digit format such as 020106, where 02 is the territory, 01 is the area and 06 is the department. I then need to take them and organize them. There is a total of 69 strings and I need a way to read them from a text file, sort them and then output as shown below (in a new text file) Any idea how I would go about doing that?
Example output:
Terr - 01
Area - 01
Department Number of Employees
01 1
05 15
06 3
Area - 02
Department Number of Employees
06 7
Terr - 02
Area - 01
Department Number of Employees
06 1
I would encourage you to break down the problem into small chunks and then solve those chunks one by one. You can do it!
Do as the video and add sorting after that , Tim also has a video showing that.
Hey Tim, love your videos. They've really helped me get information in and out of a file. One thing I'm unsure of though, is how to do you overwrite data after variables have been changed during an apps use? Would it just be a case of clearing the file before you save your data again?
The version of the save I am using overwrites the text file instead of appending to it. You can change that, though, if you want to append instead of overwriting.
Wow, quick reply. Thanks, Tim.
I found this tutorial pretty helpfull . In the last 3 years of me coding , i have not been able to make a High score system in the games i have worked on =)
Well, there you go. Now you can save your high scores.
Thanks ! can you possibly upload code files with comments ? this would really help the people who watch your videos .
Depending on the video, I do post the code but usually the code is small enough that you can follow along and re-create it for yourself. That has the added benefit of increasing your learning while providing you the code.
IAmTimCorey I totally agree with you there. For me I prefer to download videos & re watch them .
@14:33 code editor suggested:
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
Url = entries[2],
};
Yep, that is a valid alternative.
Thank you! Very helpful tutorial
Glad it was helpful!
Great video, clear explain.
Thank you!
Thanks for the video... Nice presentation.
So what is the benefit or difference of using FIle.ReadAllLines, File.WriteAllLines compared to using StreamReader, StreamWriter?
Clear explanation. Subbed
Thanks!
This is what I needed thanks!
Glad I could help!
Old video but to a an old programmer updating my skills it's gold. It re-writes the file each time. Thinking of huge text files 500MB to 1GB it would probably take forever to save. Thinking of changing it to only update the changed lines, what would you recommend I research C# wise?
How would you access just one variable out of the object? Like say I wanted the last name of the third person?
This is nice, very informative... Thanks Tim... I just want to know if one entries has comma character, what happen if I use comma as delimeter...
Things break. You have a couple options then. First, you could strip out commas before you insert the values into the text file (in case they aren't needed), you could change the delimiter (pipe is almost never used in normal typing or you could use a double character like two pipes), or you could account for it using double quotes. That last one is a bit trickier because you have to change how the split works. You would manually split the records but if you encountered a ," combination, you would not split on the next comma until after you saw the end double-quote symbol. This is how "real" csv files work.
Hi TimCorey it is very good video for beginners like me. I have a doubt where if the lines in file are of different length(15:46 time in this video), i.e more than three entries per line lets say i have four lines first line has three entry,second line has two entries the third line has five entry and fourth line has four entries. how to handle this situation..?
Well, you have invalid data then so you need to set up a rule about what happens in this case. That will depend on your application. You might ignore the row entirely, you might take the raw data and put it on the screen for the user to see in an error message, you might put that data into a textbox on a form so that the data can be modified/cleaned up, or you might do something else with it. The key is to remember that it is bad data. You cannot tell which column you are missing or which one is the extra column. Therefore, it cannot be handled automatically with confidence.
very useful. However my output file will be hundreds of lines long. Reading it in as a list, adding one line and then writing it out will take up too much time. I need to just append/add to the file by adding a new line. Any thoughts?
I have a question. If i wanted to access, for example, greg jones lastname, and change it to a new lastname, or for that matter any variable, how would i achieve that? As far as i know, list have index to access, but can i make it so, that all person also has ID variable, that is stored in the text file, and use that ID to get all the content of that particular line, and then do stuff with that line person information. Hope it makes sense.
Text files cannot be used like databases. You would need to read in the file, make the change, and then write those changes back to the file. The easiest way is to read the whole file and then overwrite the whole file with the new data.
I'm curious what you would recommend if one wanted their application to save individual files in the same manner as Excel with .xlsx, Word with .docx or Acrobat with .pdf. I believe some of these formats are simply XML documents, which is just a fancy text file, is it not? I'm currently looking at using JSON to create my "own" file format. Wondering if you have thoughts and/or suggestions for this approach. As always, thanks!
I would recommend using a tool to build those formats. You technically could create them but it would be a LOT of work. Writing to the file is the simple part. Knowing what to write is the hard part.
Very informative. Thanks.
You are welcome.
im a tad bit confused, when using
file.WriteAllLines(FilePath, output);
shouldnt it write all of the other person instances instead of just writting another greg
We do, but we are overwriting the existing file, which means the file looks like we just added another Greg, when in reality we wiped out everything, rewrote everything, and added an additional entry.
Hi Tim,
Thank you for your videos. What happens when a new object is created in a for/foreach loop? Is the first object reused? If not, then on a larger scale could creating objects in for/foreach loops produce clutter in the program, and what could be done to avoid that? The first thing I think of is creating a placeholder instance of an object outside of a loop that the can be accessed, using it to hold temporary values.
It also dawned on me to possibly add a number at the end of each instance being created within the loop so each instance has a unique name. Am I over thinking this? I would like to know how this is functioning on as low-level as I can.
In a foreach loop, the variable is getting re-initialized in every iteration. The old data is discarded and the garbage collector will clean it up. However, if you are iterating over objects (like class instances), you aren't actually duplicating the class, just the location of the class (super-efficient). No, there is rarely a case where you need to optimize a foreach loop because of the variable. I can't remember an instance where I've needed to do that. The placeholder wouldn't solve anything because it would end up doing the same exact work.
Adding a number to the variable name? No, you couldn't do that and it wouldn't be valuable to do. In fact, it would be terribly inefficient. The variable only lives for one iteration of the loop. In your mechanism, it would actually last longer (in theory).
@@IAmTimCorey I came across the term garbage collector somewhere but I haven't really thought I should look into it until now. I appreciate you clearing up some of my speculation (though there will always be more) with your response. Thank you for your time and service. Subscribed!
First of all, Thank you VERY much for your free, comprehensive videos!! I cant say how much they have helped me. I have a question that have been researching and could not find the answer for it.
I have a program that generates a text file and I want to create report based on that text file. I have found Microsoft report viewer but I am not sure how to use it with my text file. I dont want to pass the whole text file to the report viewer, rather pass some parts of it and create a table out of it in my report. I would greatly appreciate any help.
It sounds like you should create a second text file that is the one you run through report viewer so that you don't have to worry about reporting on the whole thing. As for creating a table out of the data, that's something you will have to play around with. Maybe create a CSV file and have report viewer parse it?
Thank you very much for your quick reply. Can I pass images to report viewer as well. Is there a tutorial on how to do that? Since I want to pass some images as well as the text file combined together.
Hi Tim, what if two fields in the text file are numbers and you wanted to calculate the sum of the two numbers in a new field then output that into the same text file?
I'm not sure what the question is. Yes, you can do that. You just need to build the logic to do so.
Hi Tim! ReadAllLines is not useful if it is a huge file, and we probably need to read it in chunks with an open connection. Can you make a video on that?
I added this to Tim's list of viewer suggestions for future videos. Thanks for sharing.
Great video. Is this the same as serialization? It would be great if you could do a video on XML, JSON, and other types of serialization. Also, how to read and apply a configuration file. Keep up the great work!
Not quite the same as serialization but close. More semantics than anything. Thanks for the suggestions.
Hello, what is the best way to extract text from PDF or Docx files?
Was the class Person declared from another file? I tried doing this code but when I typed the word Person it says "The type or namespace 'Person' could not be found"
If Person is a in a different namespace, you need to add a "using" statement at the top to point to the correct namespace.
Thnx sir. Your teaching methods good. Please create a video on firebird database connectivity with c sharp
I will add it to the list. Thanks for the suggestion.
can I also access one line? for example FirstName from line 2?
Hi, nice video.
Just a quick question - is there a way to print to the console only one list item (eg. line 9 in the FirstName list)?
I'm not sure I understand the question. Yes, you get to choose what you print to the console. You can print just one object or even just one part of one object to the console.
"Assuming is the mother of all problems when it comes to programming"
-The best quote of all times
It is one of Tim’s Software Development Commandments. The next is “Don’t trust the user”.
This is easy and all i knew all this stuff before the video... But how do you read a different kind of data in a separate lines e.g. when you got a text for several lines and then an array. How do you sort that kind of information because parts[0], parts[1] etc is not going to work anymore. Also how to store delimiters to a result file aswell?
You need to write the logic to parse it yourself. Or you can save it in a known format like JSON and then have a pre-built parser do the work for you.
thank you :)
Dear Tim Corey,
Is there any way to insert a string into a specific row location of a .csv file?
(e.g. I want to insert a string to the second row of a CSV file which has 10 rows data)
The easiest thing to do would be to read all of the lines and then do the insert in your List in C# and then write all of the lines.
@@IAmTimCorey but my csv file is pretty big (maybe over 10.000 lines), and I just want to modify the second line of it. It's a bit risky if I change all the content of the file just to modify a single line.
Very informative video helped me out a lot, but I have a question. Is there a way to pass text from the file into a 2D array. so each comma represents a column, and line represents a row to make up a table.
i.E
mammals, Dogs, cats, horses, Platypus
Fish, Clownfish, Salmon, Crayfish, Tuna
Birds, Parrots, Pigeons, Sparrows, Penquin
The point is to make an easy way to randomly choose a category and then display the elements within it.
Once you read the text in, you can put it into any structure you want.
very impressive and outstanding explanation
Can i ask is this can be used as data base from that text file?
You could use this in place of a full database if it is a small enough application. If it gets too big, it would be too fragile.
Dear Timothy,
I had to use the following syntax for displaying people using foreach loop, since my VS2010 does not support the $ format:
Console.WriteLine( "{0} {1} {2}", person.FirstName, person.LastName, person.URL );
However, trying to use the same format for writing the fields back to the file as a single string confuses me:
output.Add( "{0},{1},{2}", person.FirstName, person.LastName, person.URL );
This doesn't work, as Add takes one argument, and not four.
output.Add("{person.FirstName},{person.LastName},{person.URL}");
This doesn't work either, as the same literal strings get written back to the file.
I wonder if you could please help me figure out what to do here?
Thanks
Thank you very much indeed.
Will this work for reading .cfg files if I alter the code to look for that file instead, also would this work for Unity, since it might be using the same concept, just replace most of the logging with Debug.Log?
The code doesn't care about the file extension. If you can open it in Notepad, you can open it, modify it, and write back to it in C#. So yes, you can modify cfg files. As for Unity, not sure. I would assume so but Unity C# is a bit different than full C# (it isn't as current).
Hi, Thanks for this video .
You are welcome.
So tim with vs 2022 and .net when i ,while in project, right click, just how you did, and add class in the class. I get all the using stuff
It isn't a bug. The "using stuff" doesn't negatively impact your application.
how to read a file columnwise and to print each column to new seperate files.content of the file is Ist column is time and n number of columns .All are in float.Could u please help.
There are multiple ways to do this. I would use Regedit to parse the text line for columns but I'm an old PERL programmer.
Hello Sir, how much significant it is know what happens behind scenes while programming applications. Like how variables will be stored in stack ,heap.Is it necessary to know underlying details in most of applications?
It is not really necessary for the most part. The biggest thing to understand is performance basics. For example, I know that appending one string to another is an expensive operation. That is good to know so I don't do that in a loop. Otherwise, I could make my application really slow. I also know to create only the variables I need, not tons of extras that will just clog up the memory (although .NET is good about getting rid of unnecessary variables). However, I don't concern myself too much with the deep dive memory management stuff, nor do I recommend that others do so. Focus on writing good C# using best practices. Those best practices are sometimes based upon performance. You don't need to know all the details to use them. That way, you can focus on writing good applications. If you spend too much time worrying about the obscure details, you won't have as much time to write the great programs.
IAmTimCorey thank you so much for great inputs. I always like you how you explain in detail to every question we ask. You are one of awesome RUclips programming channels in the world. Thank you teacher :)
Hello Sir, I have one doubt. It might be a dumb question.
Suppose we have two classes in same namespace like in the image imgur.com/a/Z8hhzKz, I cant instantiate Program class object directly inside Program2 class without writing inside some method like constructor. What is reason for this, is it that all code inside class should be inside a method?
I couldn't figure out why. Thank you
Yes, all code except variable declaration and initialization needs to be inside a method. Also, you are instantiating a new Program class but you don't need to do that to call Main. Main is static so you can just say Program.Main() to call it.
Thanks for answer. This cleared my doubt.
Thanks for this video.
I have problem here> I am using a Visual Studio 2012. When i type:
Console.WriteLine($"{person.FirstName} {person.LastName}: {person.Url}");
i get error: Unenspected character '$' If i change to:
Console.WriteLine(person.FirstName +""+ person.LastName+":"+person.Url);
it is works. What is the problem? version VS2012 or something else ? Sorry, english is not my native language.
Best regards
Yep, the issue is Visual Studio 2012. String Interpolation (using the $) was introduced in C# 6.0 (Visual Studio 2015). If you are stuck using Visual Studio 2012, you will need to either do what you figured out (which isn't very efficient so don't do it in a loop) or you could use the string.Format method (which is built right into Console.WriteLine or you can call it manually at any other point). Your line would then look like this: Console.WriteLine("{0} {1}: {2}", person.FirstName, person.LastName, person.Url);
However, if you aren't restricted by your company or the age of your computer, go to www.VisualStudio.com and download Visual Studio 2017 Community Edition. It is free and it will give you all the new features available in C# 6.0 and C# 7.0 as well as all the improvements to the tooling.
Use person.FirstName.Tostring() ect ...
Hey Tim, what's the difference between using a streamwriter/reader or just simply using File.(...) ? Both can achieve the same thing. And thanks for the videos, great help!
Depends which type of method you are using with File but it can just be simplicity.
I'm getting System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect. error.
I copy and pasted the file path name from the properties to the code and checked multiple times to make sure it's correct.
Couple of things. First, be sure there aren't single slashes unless you are using the "@" symbol in front of your string since slash is an escape character. Next, verify that the path actually exists by going to File Explorer and pasting it in (fixing the slashes if you need to).
@@IAmTimCorey
Finally got it to work using:
*string filepath = Path.GetFullPath(@"C:\Demo\Test.txt");*
*string filepath = @"C:\Demo\Test.txt";*
was not doing it at all. I'm using Visual Studio Version 16.5.0.
Thanks for your response and keep up the good work. Definitely, be watching more of your videos.
@@quantomic1106 I just updated to this version to see and it works fine for me.
string filePath = @"D:\C_Sharp_Tutorials\Play Files\test.txt";
@@scientist100 Tried it again without the Path.GetFullPath and now it works. Don't know what the hell was going on. I used the same path. Literally, the only thing that was different was using the Path.GetFullPath.
@@quantomic1106 glad it worked, I'm learning C# and this course appears to touch all basics of C#, I'm very familiar with VB.net and actually develop in the VBA environment but I'm thinking I should use stand alone applications for reliability and to connect multiple users at the same time. The set-up that I have is a bit weird but it becomes complex but I'm the one that knows what happens behind the scene of the application.
Let's say I want to have a Link on a GUI open that textfile. How would I designate the path so that anyone who runs the program can open it? Since the file path may not always be the same depending on where on person saves the project vs where I saved it. I keep the text file in a textfiles folder inside of my project folder.
Well, if it is a known location relative to your executable, you can use a relative path. You can also have the user find the text file the first time they use the application and you can store that information (the file path) in the app.config file (or you can do it on install).
Wow, that was fast and very helpful. Thank you!
Hello, Tim! First of all, thank you for this video, it really helped me out a lot on a project i'm working on. I have a question though. I want to be able to search for the first element in the file and have the program return the rest of the line to me.
Here is an example -
Die: 747 measurement: 266.7 Notes: Some sample note here.
Something like this but I want to search by die, in other words, the first element. Thanks in advance. Best of luck to you.
Load all of the lines into an array and then just do a search on each one for the starter text.
@@IAmTimCorey Ok, thank you. I'll try that. I'm also having a really hard time using this code in a try catch block and at the same time creating the file. Any suggestions?
Hi awesome video helped me a lot already but how do i handle the problem, when i only know what my 5 first columns are and after that i can have unlimited more columns?
So i know my first couple columns are name, last name, street, etc. and after that i get for every file i want to load a different amount of columns that i dont know anything about.
Not a problem. Since you read each line in as a full line and then split on the separator (usually the comma), you can have as many columns as you want. You probably cannot create class properties for each column but you can have an array property that handles all of the "extra" columns.
There is a .txt file with many variables in it, and I want to display the value itself but when I do this it displays the whole line. Any tips?
Cheers.
It sounds like you need to parse the data in the line. You get the whole line, now pull out just the piece you need.
Hey guys , in case you guys need the code . here it is linked below . The file name i have used is different so keep that in mind .
hastebin.com/nomewuxeci.cs
Nice!
Hey, how would you Save then load a file from buttons (click events)? Thanks in advance
I am not sure I understand the question. I demonstrated how to read from and write to a text file. To do it with a button click event would just require that you call those methods from the event.
Adding to a string array is difficult so you used a List Collection. But why didn't you use StringBuilder type which easily supports adding data ? Kindly answer.
A StringBuilder works if you are doing one line. I wanted to add one line per row of data. A list is the easier way of doing that. You can use the line returns in StringBuilder but it isn't as clean.
@@IAmTimCorey Thanks for answering.