views:

82

answers:

2

i have stored the txt file to sql server database . i need to read the txt file line by line to get the content in it. my code :

DataTable dtDeleteFolderFile = new DataTable();
dtDeleteFolderFile = objutility.GetData("GetTxtFileonFileName", new object[] { ddlSelectFile.SelectedItem.Text }).Tables[0];

foreach (DataRow dr in dtDeleteFolderFile.Rows)
{
  name = dr["FileName"].ToString();
  records = Convert.ToInt32(dr["NoOfRecords"].ToString());
  bytes = (Byte[])dr["Data"];
}

FileStream readfile = new FileStream(Server.MapPath("txtfiles/" + name), FileMode.Open);

StreamReader streamreader = new StreamReader(readfile);
string line = "";
line = streamreader.ReadLine();

but here i have used the FileStream to read from the Particular path. but i have saved the txt file in byte format into my Database. how to read the txt file using the byte[] value to get the txt file content, instead of using the Path value.

+1  A: 

Given th fact that you have the file in a byte array, you can make use of MemoryStream Class

Something like

using (MemoryStream m = new MemoryStream(buffer))
using (StreamReader sr = new StreamReader(m))
{
    while (!sr.EndOfStream)
    {
        string s = sr.ReadLine();
    }    
}

Also make sure to use using Statement (C# Reference)

Defines a scope, outside of which an object or objects will be disposed.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

astander
A: 

You could try something like this at the end of your foreach:

String txtFileContent = Encoding.Unicode.GetString((Byte[])dr["Data"]);
Colin Pickard