IntroductionIn the .NET Framework 4.0 have lots of new features for software professionals. Today I would like to share I/O operation in File class. Method No 1:File.ReadLinesThis is new method in .NET Framework 4.0 with File class. This method accepts the path of the file to read and encoding. Then it will return the collection of IEnumerable<string>. Method Definition //// Summary:// Reads the lines of a file.//// Parameters:// path:// The file to read.//// Returns:// The lines of the file.//// Exceptions:// Few no of exception has applicable[SecuritySafeCritical]public static IEnumerable<string> ReadLines(string path); CodeSnippet using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace ConsoleApplication1
{class Program{static void Main(string[] args){// New Features in for IO -ReadLinesvar lines = File.ReadLines("File.txt");foreach (string item in lines){Console.WriteLine(item);}}}} Method No 2:File.WriteAllLinesThis is old method, but it accepts the new parameter to write all lines from source content. When we are calling this method in .NET Framework 4.0, we will able to pass IEnumerable <string> as one of the argument. CodeSnippet using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace ConsoleApplication1
{class Program{static void Main(string[] args){// New Features in for IO -ReadLinesvar lines = File.ReadLines("File.txt");// New Features in IO-WriteAllLines, with IEnumerable File.WriteAllLines("desti.txt", lines);}}} Method No 3: File.AppendAllLinesThis is another new method in .NET Framework under the File class. To this method can pass the destination file path and IEnumerable <string> collection. Method Definition // Summary:// Appends lines to a file, and then closes the file.//// Parameters:// path:// The file to append the lines to. The file is created if it does not already// exist.//// contents:// The lines to append to the file.//// Exceptions:// Few no of exception has applicable[SecuritySafeCritical]public static void AppendAllLines(string path, IEnumerable<string> contents); Code Snippet using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace ConsoleApplication1
{class Program{static void Main(string[] args){// New Features in for IO -ReadLinesvar lines = File.ReadLines("File.txt");// Just appened read lines in to the file with IEnumerableFile.AppendAllLines("sasds.txt", lines);}}} That’s all and I like these features, because reduce no of lines code to perform I/O operation, enjoy the new features in .NET Framework 4.0. I will post more new features in future as well. |