C# Data Access: Text Files

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in c-sharp data-access using a text file is really simple in fact to read from a text file it takes one line and again to write to a text file takes just one more line so I got demonstrate how to do this these one-liners and then how you can use a text file to really save and use data in c-sharp we're going to start with this text file here test dot txt inside here I have two lines of text and if you notice it's common delimited we're going to skip over why it's comma delimited for now we'll come back and actually break that apart later and use it but for now we're just going to read this as two different lines of text so how do we do that let's start with a console application I'll call this console UI and my solution name I will call text file data access demo and the first thing I do in a console applications I come over here and at the end I say console read line and what that does it just stops the console from closing out before I've read with on a screen now the reason I chose a console application is because it's very very simple to get started there's not a lot of overhead or extra stuff that needs to happen so let's start by looking at how we can read from that text file now if we go back to where that text file is note this in C demos so the full path is C demos text dot txt let's go ahead and create a variable to hold that now here's where things get a little bit tricky if you're not used to dealing with strings if I were to type C colon slash demos slash test.txt note that i get the red squigglies under each of the slashes and the reason why is because the slash is a special character it's an escape character if I wanted to actually have a slash there I could do a double slash and that works but it looks kind of ugly the other option is in front of this string you can put the @ symbol and that just says this string is a string literal there's no escape characters in there so it's up to you which way you do it but if you see this symbol somewhere in someone else's code just that means it's a string literal alright so there's our file path so now how do you read from a file well you need to have a using statement for system do and then we can say file dot read all lines and you get a path and that's it so file dot read all lines in getting the file path will return an array of strings now we could say string array lines equals file dot read all lines the thing is that a string array is kind of difficult to work with so I usually prefer to use a list of string now that's not the return type of retail lines but at the end of this if we hit dot to list and call that helper method it will convert this array of string to a list and the reason I like to do this is because I like to add to my list potentially and adding to a string array is it's just a little bit more difficult so let's make sure this works so I'm gonna do a for each and I'll say string line in lines and this was loop over every low line in my list of string and let's just do a console.writeline right out that line so all I'm doing here is reading all the lines from the text file this right here I'm converting to a list putting it in this variable then I'm looping through that variable one line at a time using the for each and for each line I'm writing that to the console if I run this I get those two lines line 1 line 2 now what if we wanted to write back to that text file well that's fairly simple the code for that is file dot write all lines we gave it the file path let's give the same file path and then we give it either a string array of contents or we can do an ienumerable of string well a list of string is an ienumerable so you can pass directly in our lines variable and that will write those lines now it's going to write to the same location so how we know that things have actually happened well above here we can say lines dot add let's add a new item now I kinda limit it with three values let's do su comma storm comma W W stormy calm okay so I have three values that are common delimited in my text file those three values our first name last name and some type of URL that's what I already have I'm going to add one more line so I'll add a first name comma last name comma some type of value so I've added this to my list of string so this should be at the end I should now have three lines written to my text file let's run this it completed we don't have any output to show us that we wrote but if we close this out we open up our file again we now see we have three lines Tim Cory Joe Smith and now Sue Storm and that new URL so it works so reading from a text file this line right here writing to a text file this line right there now happy make use of this in a more comprehensive or more real-world type scenario let's go ahead and comment this out let's start over again but this time I'm going to create in my console a new class let's call this person all right so I've created three properties inside the person class the first name last name and a URL now if you think back to my text file let's open that up again I have what looks like a first name a last name and a URL so I'm kind of basing off I already have let's first think of how we could access the data from that text file to populate a list of type person so that's a list of person is our goal call people so how do you populate this list of person well I would start with saying list of string lines equals file dot read all lines oops we commented out file path up here now convert that to list it's the same lines right here is retyped it but now in my for each I'll still do line in lines and you can keep this VAR if you want or you can convert to a string it's going to change itself to a string at runtime anyway it's up to you but now in here I'm going to say string array entries equals line dot split and the splits on the comma separator what that's going to do is going to split this line into multiple entries based upon the comma delimited if we look back at our text file we read this line right here in it's going to go into the first entry in this lines list next way to the for each the first entry this line right here we put into the line variable then we'll take that line variable and split it on the comma so this right here and this right here and that resulting array will be put in this stringer right here called entries so entries will have an entry for Tim it will have an entry for Corey you'll have an entry for the WWI um Corey com it will do that for every single line once we've done this then we can say person new person equals new person new person dot first-name equals entries zero having with zero well we open that text file up and found it's the first item in the comma delimited list new person dot last name equals entries one and new person dot URL equals entries two and then finally people dot add new person so we're doing here is for every line we're going to split apart in the comma and then when I create a new person entry we're going to populate it with first name last name and URL from the entries array from the values found there at the zero one two positions and it will add that to our list of people just to show that this will work let's do a for each let's do a console.writeline and this time I'm going to do the dollar sign format this is a new format to see Sharps 6.0 if you haven't seen a four what you can do is put a dollar sign in front of your double quotes and then inside of your string you can add these entries where you have a curly brace and inside curly brace you can put actual c-sharp code so this case is going to put person first name after the cria brace up to a space and then person dot last name close curly brace and mail put a colon space and then that URL so what's going to happen here is because we use this dollar sign here these curly braces kind of escape out of the string and allow us to put c-sharp code which will get then put in this place so it's going to take this out and put the value for first name in a spot and notice a space here because we're still inside these double quotes which definitely treated like a normal space inside double quotes now had a last name a lot of colon space and then the URL so these gets replaced right here with actual values this would be equivalent if you want to look at this way of saying person dot first name plus double quote space double quote plus person dot last name plus double quote colon space double quote plus person dot URL inside of this right here okay so that these two are equivalent as far as outcome they are not equivalent as far as speed this right here much slower much much slower this is a great new syntax let's run this just to see what happens so the idea here is we read from that file we put that into a list of string and then for each line in there we're going to split it apart and create a new person entry based upon the split-apart entries once we've created that list of people we're now going to iterate over it just to show that we do have an actual list of people let's run this and now we have that list of people tim space corey colon space WWI m2m Corey calm so now we have read from a CSV file or a text file that's comma separated and they've put that into an actual list of strongly typed object in this case type person now the one thing I want to point out right front is the idea that right now I have no error checking on this list I'm assuming which is always a bad thing when your return on programming but I'm assuming that it has three entries per line if it didn't this could cause a problem to actually crash the application so I would definitely recommend that if you do this method that you check to make sure you have the proper number of entries per line now if you didn't that probably means you have invalid data so in which case you wouldn't want to create a person maybe you wouldn't even want the application to continue maybe you want to stop and say wait let's let's redress this first but this might be as simple as surround us with a try-catch or by checking to make sure that entry count is always three so entries dots length I believe entries dot length they'll give you the length of the array and so if length is three then you're good otherwise you can probably throw an error of some type if you want to be lazy about it and not give a great error message you could leave it without any type of error handling like Lee is here and it will crash but it will crash with a index out of range error so that wouldn't be good it also wouldn't catch any error where you had extra information on line maybe the person put middle name so first name middle name last name will that be a problem because middle name be treated like last name and last name would go in the URL spot and that's not we want so if you made sure that the entries lists only had three items so it had no less than and no more than three items otherwise you throw an error because it's unexpected so just some things to think about always make sure you have good error checking on your application don't just soon things will work assuming is the mother of all problems when it comes to programming so off my soapbox there right now we have a working application that is converting our existing text file to a list of strongly typed person objects but what if we wanted to go the opposite direction what if we said okay we have our people and let's just do a console.writeline here read from text file so we know that that's where we're at and now we're going to do is add a new person to our list so people dot add new person add Greg Jones and Greg's URL is wowt.com all right if you're not familiar syntax what I'm doing here is I've got a list of people each of type person and saying list dot add and it expects a person object but I don't have a person outted yet no worries I'm going to write in line create a new person this creates a new instance it's called an anonymous instance because it doesn't actually get assigned to a variable name instead once we do this right here it replaces this whole line with that new instance which then gets added to our people ray or people list so I say new person then I use my curly braces which allows me to set the value of properties so property one property number two and property number three right at creation so I send my first name my last name and my URL it's just a really neat little shortcut that allows us to create a class pretty quickly so I've now added a person to my people array how would I then take this value or this whole list of values and save it back to that same text file well we can do the basically the same process but in Reverse so let's create a list of string we'll call it output we're going to do is we're going to do another for each we're a loop of that same list of people because that's the list that's now been updated and this new person Gregg we're a loop over that whole list and for each person we're going to add an entry to the output list remember that's up here file that right outlines we can pass in a list of string it's going to create that list of string here so output dot add and here to recreate our string so I'm going to do a dollar sign and then two double quotes place tentacle on the end so I have it now all we need to do is create a strength person dot first name I'm doing my Cree braces in order to have that be substituted and then outside the curly brace I'll put a comma and open the next curly brace it's a person dot last name closed curly brace comma oops no space person dot URL and no comedy at the end so we have first name comma last name comma URL for each one of these people now I have a list of string output which means that I can say writing to text file and then right down here go to the same code is right here so file dot right all lines I'm going to pass in the path file path which again is that variable it's right up here use the same file name and I'm going to say instead of a string array I'm going to pass in my output which is an ienumerable more specifically it's a list of string so there you go and now I'll just put a console.writeline at the end just to say a line tree is written okay if we run this read from the text file there's the 1 2 3 entries now it says writing to text file and now all entries have been written it's very quick we go over here to our text file we now say Tim Cory Joseph Smith Sue Storm and Greg Jones and in fact if we run this again we're actually going to add another entry for Greg Jones because now we read Greg Jones in and they write to him again so we've already read into four lines and now they reading this we write the fifth so that is reading from and writing to a text file and here's how you can actually make use of it to store data and then repopulate time the application loads or whenever you need to access information so really if you want to you could use text files as a cheap data storage solution without having to look at things like databases and installing things making sure things are working and all the rest the complexities that come along with a full fledged database if you have any questions about this leave a comment below ask the question and I'll get back to you as soon as I can if you have a suggestions for other videos you'd like to see definitely leave those in the comments down below as well also if you want to have heads up on new things are coming out from me make sure to jump on a mailing list my mailing list URL is in the description of this video as always I really appreciate you watching and I would really appreciate if you'd subscribe as well thanks
Info
Channel: IAmTimCorey
Views: 210,690
Rating: undefined out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, c#
Id: cST5TT3OFyg
Channel Id: undefined
Length: 24min 34sec (1474 seconds)
Published: Wed Nov 02 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.