Console I/O8:12 with Carling Kirk
Learn about streams in the Console class and use StreamReader to read from a file.
Let's play around with the console a little bit. 0:00 We'll delete what we did before and we'll print out hello world. 0:04 I know, I know, 0:08 you've probably done this at least ten times already but bear with me. 0:08 Console.WriteLine and "Hello, world!". 0:12 So what is the console class exactly? 0:19 We've been using it this whole time in other courses, but 0:22 what is actually going on when we tell it to read or write? 0:25 Well, we can gather that read is the input part of our IO and 0:29 write is the output, right? 0:33 Let's take a look at the documentation on the Console class by hitting F1. 0:35 Represents the standard input, output, and error streams for console applications. 0:42 So not only do we have an input and output stream, we've also got an error stream. 0:47 Let's go back to our code and open up our data.text file. 0:53 But we'll take Hello, world from our String here and cut it with Ctrl+X. 0:59 Paste it here with Ctrl+V. 1:05 Okay, now we can change the input stream of our console with a method on 1:10 the console class called SetIn. 1:15 But we need a stream first. 1:20 We need an input stream from our text file. 1:22 There's a handy class we can use called Stream reader, Stream reader. 1:25 Let's check out its documentation by hitting F1, implements a text 1:33 reader that reads characters from a byte stream in a particular encoding. 1:38 We'll talk about what it means by encoding in a bit but 1:42 let's take a look at the constructors. 1:45 That's a lot of constructors. 1:48 We're looking for one that takes a file name. 1:50 Well, here's a string, initializes a new instance of the stream reader class for 1:53 the specified file name. 1:58 We can try and use that. 2:00 First we need to get the filename. 2:02 We can use the file info class to get a single file and 2:03 make sure it exists before we try to read it. 2:07 We'll instantiate a new file info objects. 2:09 So, file = new FileInfo and it looks like it takes a file name in the constructor, 2:12 says the fully qualified name of the new file or the relative file name. 2:22 Do not end path with the directory separator character. 2:27 Got it. 2:31 We'll create a new variable to hold the file name, var filename, 2:32 we'll use the Path.Combine method, Path.Combine, 2:38 we'll give it directory.FullName and 2:42 the name of our file, which is data.txt and semi-colon. 2:48 It's a good idea to use Path.Combine when you wanna filename 2:57 because it will add the backslashes for you if they're missing. 3:00 We can pass the fileName into the FileInfo constructor, and to be safe, 3:04 we should check and make sure the file exists before trying to access it. 3:09 Let's see if there's a property on file that we can use. 3:13 file.Exists. 3:16 It returns a boolean, so we can write an IF statement, 3:20 if file.Exists, and open close curly brace. 3:24 Now we can use our StreamReader class. 3:31 var reader = new StreamReader, and 3:33 we'll pass it the file.FullName, 3:37 then we can use the SetIn method of the console class. 3:42 Console.SetIn, and we'll pass it the reader. 3:48 We'll delete this down here, too. 3:56 Now that our console input stream is set to our data.txt file, 3:59 we'll write the contents of the file to the console. 4:03 Console.WriteLine and 4:07 Console.ReadLine. 4:11 And semi-colon. 4:18 There's one final thing that we should do before we try to run this. 4:22 There is a method called close that we should call 4:26 once we're done with the stream reader. 4:29 What this does is mostly self-explanatory, it closes the stream and 4:32 it also releases the resources that are being used to read the stream. 4:36 When we deal with streams and files, we're using unmanaged memory. 4:41 In .NET, objects aren't cleaned up immediately when they're no longer needed. 4:46 It's more efficient to only clean up those objects when the computer is in need of 4:51 the memory, so it will wait as long as possible before cleaning up these objects. 4:55 It's very difficult to predict when this might happen. 5:00 The part of .NET responsible for 5:03 cleaning up these objects is called the garbage collector. 5:05 Files are unmanaged, meaning that they're not managed by the garbage collector. 5:08 We have to tell the garbage collector that it can take out our trash, and 5:13 we do that by calling the close method. 5:17 This will also let other programs on the computer use the file. 5:20 One way to know if something is unmanaged is to check to see if it implements 5:25 the interface IDisposable. 5:29 Let's click on StreamReader and go to definition. 5:32 It inherits from text reader, let's go to definition, 5:37 aha, there it is, IDisposable, 5:41 though an easier way to tell is to just check intellisense to see if it exists. 5:46 Reader.Close. 5:51 So now we just need to call it. 5:55 But what would happen if an exception is thrown after our StreamReader is created, 5:58 but before our call to close it? 6:03 Close would never be called and we'd never an open file with no way to close it. 6:06 In order to ensure that Close is called, even in the event of an exception, 6:11 we need to wrap this code in a try finally. 6:16 Try, And finally 6:19 The finally block guarantees that any code inside of it will get executed, 6:30 even if there's an exception in our try block. 6:35 You can use it with or without a catch block. 6:39 But instead of having to call the close method, 6:42 there's an even better way to do this. 6:45 We can declare and instantiate the disposable object with a using statement 6:48 surrounding a block of code. 6:53 So up here, using and then at the end, 6:55 Close paren and then our block of code and we can move our 7:02 try block in there and we can delete all of this. 7:10 >> When the program gets to the final curly brace of the using block, 7:16 the dispose method of the stream reader object will be called. 7:20 The dispose method will then call the close method, and the file will be closed. 7:24 So here when we call Console.ReadLine, 7:28 instead of reading from the prompt, it's gonna read from our text file. 7:31 Let's run it to see what happens. 7:37 Ctrl+F5 and there's our Hello, world. 7:39 So what happens when we try to read from the stream after our using blog? 7:45 Let's try it out. 7:49 Console.ReadLine. 7:50 And again we'll run with Ctrl+F5. 7:57 No. 8:02 We get an ObjectDisposedException: Cannot read from a closed TextReader. 8:03 The stream was closed by our using statement. 8:09
You need to sign up for Treehouse in order to download course files.Sign up