Showing posts with label C# complete File Handling. Show all posts
Showing posts with label C# complete File Handling. Show all posts

Sunday, June 12, 2011

C# complete File Handling

C# File Handling
You need to handle file IO in your application written in the C# programming language, utilizing the .NET framework's powerful methods. Test the methods in the System.IO namespace and also look at some performance issues. Here are many file handling examples and some benchmarks of the System.IO namespace from the base class library.
Add using System.IO
First, my experience is that the .NET Framework provides excellent file handling/IO methods. They are optimized in the framework so that you don't need to hand-optimize buffer sizes or other mechanics. Make sure to include the IO namespace, as shown here.
System.IO namespace [C#]

//
// Include this namespace for all the examples.
//
using System.IO;
Various file methods
Here we see a table showing some of the most useful and popular File methods available. Many C# programmers use these methods quite extensively, particularly the ones dealing with lines and text.
File.ReadAllBytes
Useful for files not stored as plain text. See example near the bottom.

File.ReadAllLines
Microsoft: "Opens a file, reads all lines of the file with the specified encoding, and closes the file."

File.ReadAllText
Returns the contents of the text file at the specified path as a string.

File.WriteAllBytes
Not covered here. It can be used in conjunction with File.ReadAllBytes.

File.WriteAllLines
Stores a string array in the specified file, overwriting the contents. Shown in an example below.

File.WriteAllText
Writes the contents of a string to a text file.

File.AppendAllText
Use to append the contents string to the file at path. Microsoft: "Appends the specified string to the file, creating the file if it doesn't already exist."

File.AppendText
Not covered here in this article. You can also use standard StreamWriter code.
Read lines with File.ReadAllLines
Here you want to read all the lines in from a file and place them in an array. The following code reads in each line in the file "file.txt" into an array. This is efficient code, but this article contains performance metrics later on.
Program that uses ReadAllLines [C#]

using System.IO;

class Program
{
    static void Main()
    {
      // Read in every line in

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...