Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert varbinary back to .txt file

I have a database (SQL 2008) where I store file's in. These are saved as a varbinary(max) type.

Now I need to get the .txt file again so I can loop through the contents of the file like i used to do with StreamReader.

while ((line = file.ReadLine()) != null)
{
string code = line.Substring(line.Length - 12);
}

But how can I convert the varbinary byte[] back to the normal .txt file so I'm able to go through the contents line by line.

I found some ideas with memorystream or filestream but can't get them to work.

Thanks in advance!

like image 971
Robin Avatar asked Oct 18 '11 07:10

Robin


3 Answers

MemoryStream m = new MemoryStream(byteArrayFromDB);
StreamReader file = new StreamReader(m);
while ((line = file.ReadLine()) != null)
{
string code = line.Substring(line.Length - 12);
}
like image 185
Ovidiu Pacurar Avatar answered Nov 06 '22 13:11

Ovidiu Pacurar


try this:

System.IO.File.WriteAllBytes("path to save your file", bytes);
like image 31
ojlovecd Avatar answered Nov 06 '22 13:11

ojlovecd


cv is a varbinary(max) field

SqlCommand sqlCmd = new SqlCommand("SELECT cv FROM [job].[UserInfo] Where ID = 39 ", conn); 
SqlDataReader reader = sqlCmd.ExecuteReader(); 

if (reader.Read() != null)
{
    byte[] buffer = (byte[])reader["cv"];
    File.WriteAllBytes("c:\\cv1.txt", buffer);
}
like image 29
Iman Avatar answered Nov 06 '22 11:11

Iman