Convert varbinary back to .txt file
Asked Answered
B

4

6

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!

Bawcock answered 18/10, 2011 at 7:8 Comment(1)
See the answers to this question to know how to convert it back to string: #4959753Rattlebrained
D
6
MemoryStream m = new MemoryStream(byteArrayFromDB);
StreamReader file = new StreamReader(m);
while ((line = file.ReadLine()) != null)
{
string code = line.Substring(line.Length - 12);
}
Dogvane answered 18/10, 2011 at 7:15 Comment(1)
well, that was easier than I thought, had to make it way to complicated for me Although I noticed that there are inserted white spaces at the end of the lines and another white space between every line. But that's easy fixed. Thanks!Bawcock
M
5

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);
}
Malissamalissia answered 17/9, 2014 at 4:49 Comment(0)
W
4

try this:

System.IO.File.WriteAllBytes("path to save your file", bytes);
Wireman answered 18/10, 2011 at 7:15 Comment(0)
E
0
    static void Main(string[] args)
    {
        GetData();
    }
    public static void GetData()
    {
        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["main"].ConnectionString);
        conn.Open();
        string query = "SELECT FileStream FROM [EventOne] Where  ID=2";
        SqlCommand cmd = new SqlCommand(query, conn);

        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        byte[] buffer = dt.AsEnumerable().Select(c => c.Field<byte[]>("FileStream")).SingleOrDefault();
        File.WriteAllBytes("c:\\FileStream.txt", buffer);
    }
Exorcism answered 6/12, 2015 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.