Pages

Feb 1, 2008

load an array of strings to a text file (one string value per line) and vice versa

Hi friends this is a simple idea of loading a string values from an array to a text file and re -loading the lines in the text file to a string array and printing it..

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace StringArrayToFileAndwiseversa
{
public class Program
{
static void Main(string[] args)
{
string path = @"E:\Projects\rao.txt";
string[] str = {"rao","ram","raj","sundu"};
//StreamWriter sw = new StreamWriter();
ArrayToTextFile(str,path);
TextFileToArray(path);
}
// To load a array of strings to a text file
public static void ArrayToTextFile(string[] str1, string pathFilename)
{
StreamWriter sw = File.CreateText(pathFilename);
foreach (string str in str1)
{
sw.WriteLine(str);
}
sw.Close();
}
// Extract each line in a text file as an string array element
public static void TextFileToArray(string path)
{
string[] text = new string[10];
int i = 0;
StreamReader sr = File.OpenText(path);
text[i] = sr.ReadLine();
while (text[i] != null)
{
Console.WriteLine(text[i]);
i++;
text[i] = sr.ReadLine();
}
}
}
}

No comments: