Hello members! This tutorial is a bit nostalgic to me. Here is one of the few reasons why I am into .NET programming so much, instead of Java or C++ for example. I want to show you the File class, which is a small thing but makes my day nice.
We need a sample file...
For a start, we need some sample file to read it. I created a new console application. Then I selected the Program.cs file in the Solution Explorer panel, and switched to Properties panel. There is a property called Copy to Output Directory. I changed it to have a copy of this file in the Bin\Release\ folder. Viola, a sample file to read it, right up.
Reading and writing with File class
Let's start with some simple code, the goal is to read a file. After writing "File" press Ctrl+. and click to import the System.IO namespace. Then you just need one line of code, which one, depends on your needs.
Displaying the file contentsCode:byte[] asBytes = File.ReadAllBytes("Program.cs");
string asString = File.ReadAllText("Program.cs");
string[] asLines = File.ReadAllLines("Program.cs");
Here are screenshots of looking up the variables that contain what was read. Look at them, and decide which one of them is useful for you at the moment.
Writing data back to files
This is again what I like in .NET the most. All writing can be done in one line of code. Unless those files weight in gigabytes, your pc will not run out of memory. You can read for example setting files, or code (.cs) files this way without worrying that it will eat up your memory.
Depending on which variable or data type you want to write, you can pick one of the lines.
Leave comments and enjoy your dayCode:File.WriteAllBytes("Saved as bytes.cs", asBytes); File.WriteAllText("Saved as string.cs", asString); File.WriteAllLines("Saved as lines.cs", asLines);
I hope this tutorial will be helpful or at least make your day a little bit less of writing code and more of enjoying your day. Comments and +rep are always appreciated.![]()


LinkBack URL
About LinkBacks










Reply With Quote








Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum