Click here to Skip to main content
15,904,346 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to generate a script that will insert data into SQL 2008 database. Everything is working fine except that I am storing files in the database in a varbinary field. I extract the data but when I try run the scripts it just freaks out. This is how I am doing it.

C#
using (StreamWriter sw = new StreamWriter(Console.ReadLine() + ".sql"))
            {
                foreach (File b in context.Files)
                {
                    sw.WriteLine("INSERT INTO [File] VALUES ({0}, {1}, {2}, {3})", b.FileID, b.FileName, b.MIME, ASCIIEncoding.UTF8.GetString(b.BinaryData));
                }
                sw.Flush();
                sw.Close();
            }


Any help would be great!

Edit:
I don't need to execute the script, I just need to write it to a file. The exception is not thrown in the app, I just need to know how to write the content from the varbinary in such a way that I can execute the scripts to add ot to another db at a later stage.
Posted
Updated 29-Oct-11 8:49am
v2
Comments
Sander Rossel 29-Oct-11 14:49pm    
Please don't answer your question with another question. I have updated your question for all to see.
Sander Rossel 29-Oct-11 15:00pm    
See my edited answer. Hope it helps! :)

1 solution

Am I missing something? That StreamWriter does nothing. You write to it, then Flush, Close and Dispose. Also, where does the context.Files come from? Your question mentions Entities which leads me to think context is an ObjectContext and File is a Table in your Database.
So what does this code do? It iterates through the File table records, writes a SQL statement that inserts the already existing records into the same table to a Stream, then Disposes of the Stream the end.

So what is context exactly and what are you trying to achieve? If I read this I cannot conclude, but that this code does nothing except, throw Exceptions. Could you mention the Exception too?

Edit; OP has edited his question.
The following code will create a new .txt file on the C:\ drive. It's initial text will be "Test", but every time the code passes this again "Test" will be appended on a new line.
C#
string s = "Test" + Environment.NewLine;
using (System.IO.FileStream fs = new System.IO.FileStream(@"C:\MyFile.txt", System.IO.FileMode.Append)) {
    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(fs)) {
        writer.Write(s);
        writer.Flush();
        fs.Flush();
        writer.Close();
        fs.Close();
    }
}

I suggest you build the String in your loop and then use this code to append it to your file.
Hope this is what you are looking for/what you need.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900