Thursday, September 10, 2009

How to insert a Line of data in the middle of the Existiong Text File?

class InsertMidLine11
{
static string path = "@/../../test1.txt"; //refers to bin folder
static string data = "Line5";
static int lineno = 10;

static void Main(string[] args)
{
InsertIntoFile(path,data,lineno);
}

public static void InsertIntoFile(string Path, string Data, int LineNumber)
{
StringBuilder result = new StringBuilder();
FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.ReadWrite);
int lines = 0;
using (StreamReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (lines == (LineNumber - 1))
{
result.Append(Data);
result.Append(" | ");
}
result.Append(line);
result.Append(" | ");
lines++;
}
}
string fullstr = result.ToString();
string[] text = fullstr.Split('|');
using (StreamWriter sw = new StreamWriter(Path))
{
for (int i = 0; i < text.Length; i++)
{
string item = text[i].Trim();
sw.WriteLine(item);
Console.WriteLine(item);
}
}
}
}

That results:

Some Line1
Some Line2
Some Line3
Some Line4
Some Line5
Some Line6

Here i have to insert a Line "Some Line10" infront of the Line "Some Line5" that Looks as:

Some Line1
Some Line2
Some Line3
Some Line4
Some Line10
Some Line5
Some Line6


Note: first create test1.txt along above data and place this in the current project's bin folder.

1 comment:

Followers