Eki 21 2009

Short way of converting file lines to Array by regex. Also pay attention to usage of HashSet

Category: C#Latif @ 23:57

 

Hi again,

 

You can see the code below that simply how to convert txt file lines to array by means of regex. Also give attention to usage of HashSet.

 

Before running the code, create a txt file named myTxtFile.txt.

 

Code with comment:

 

using System;

using System.Collections.Generic;

using System.IO;

using System.Text.RegularExpressions;

 

namespace File2Array

{

    class Program

    {

        //Convert file lines to Array

        public static string[] FileLines2Array(string filename)

        {

            string[] returnArray;

            using (TextReader textReader = new StreamReader(new FileStream(filename, FileMode.Open)))

            {

                Regex regexForSplit = new Regex(Environment.NewLine);

                returnArray = regexForSplit.Split(textReader.ReadToEnd());

            }

            return returnArray;

        }

 

        //Convert file lines to HashSet

        public static HashSet<string> FileLines2HashSet(string filename)

        {

            HashSet<string> array2HashSet = new HashSet<string>();

            foreach (var item in FileLines2Array(filename))

            {

                array2HashSet.Add(item);

            }

            return array2HashSet;

        }

 

 

        static void Main(string[] args)

        {

            Console.WriteLine("Convert file lines to array");

            string[] testArray = FileLines2Array("myTxtFile.txt");

            foreach (var item in testArray)

            {

                Console.WriteLine(item);

            }

 

            Console.WriteLine("Delete duplicate lines automatically if any. Also see usage of HashSet");

            HashSet<string> testHashSet = FileLines2HashSet("myTxtFile.txt");

            foreach (var item in testHashSet)

            {

                Console.WriteLine(item);

            }

 

            Console.ReadKey(true);

        }

    }

}

 

 

See you soon...

Tags: , , ,