Showing posts with label File Write. Show all posts
Showing posts with label File Write. Show all posts

Monday, May 19, 2008

File Generation

It's going to generate a text file and save it in the similar to CSV format.

Code In-Line:

try
{
string FileName = "D:\\IENFeed_" + System.DateTime.Today.ToShortDateString().Replace("/", "-") + "_" + System.DateTime.Now.ToLongTimeString().Replace(":", "-").Replace(".", "-") + ".txt";
FileInfo fi = new FileInfo(FileName);
StreamWriter swr = new StreamWriter(fi.FullName);
StringBuilder sb = new StringBuilder();
sb.Append(len("",9),0,9);
sb.Append(len(txtName.Text, 26), 0, 26);
sb.Append(len(txtTitle.Text, 20), 0, 20);
sb.Append(len(txtCompany.Text, 26), 0, 26);
sb.Append(len(txtDivision.Text, 26), 0, 26);
sb.Append(len(txtDept.Text, 20), 0, 20);
sb.Append(len(txtBPB.Text, 26), 0, 26);
sb.Append(len(txtBPBCity.Text, 17), 0, 17);
sb.Append(len(txtBPBState.Text, 2), 0, 2);
sb.Append(len(txtBPBZip.Text, 9), 0, 9);
sb.Append(len(txtTelephone.Text, 10), 0, 10);
sb.Append("$", 0, 1);
swr.WriteLine(sb.ToString());
swr.Close();
}
catch (Exception es)
{
Response.Write(es.Message);
}


protected string len(string value, int count)
{
string output = null;
int len = 0;
len = value.Length;
for (int i = 0; i <=count-len; i++)
{
output += " ";

}
return value+output;
}

Result:

sample Admin Testing Developer abc@abc.com 12345 chennai Ta600001 12345 $

File Read & write using StreamReader

Code In-Line:

using System.IO;
using System.Text;

FileInfo fi = new FileInfo(@"D:\feed.txt");
DirectoryInfo dir = new DirectoryInfo(@"D:\");

protected void btnRead_Click(object sender, EventArgs e)
{
StreamReader sr = fi.OpenText();
string input = null;
while((input=sr.ReadLine())!=null)
{
Response.Write(input);
}
sr.Close();
}

protected void btnWrite_Click(object sender, EventArgs e)
{
StreamWriter wr = new StreamWriter(fi.FullName,true);
try
{
StringBuilder str = new StringBuilder();
str.Append(txtName.Text);
str.Append(txtPassword.Text);
str.Append(txtEmail.Text);
wr.WriteLine(str.ToString());
wr.Close();
Response.Write(str);
}
catch (Exception ex)
{
Response.Write(ex);
}
}