Getting a byte array instead of saving a byte array as a file

I'm getting a raw varbinary data from an SQL server. Firstly I'm saving it as a file, because I am loading the file and drawing a series of points on a chart. But now I also want to save it to another server when a user clicks on a button. It's terribly stupid to:

  1. Load binary data from server
  2. 'Convert' to a file
  3. Save it to a path
  4. Load from this path.
  5. Draw a chart.
  6. Load from this path
  7. Save to server.

When I could be doing:

  1. Load binary data from server
  2. 'Convert' to Byte[] or some other kind of array.
  3. Draw a chart from this array
  4. Save this array to a server.

I think it needs to be a byte array though, as the server I'm loading from and the server I'm saving to has the datatype varbinary(max). I've attached an image of what exactly I wish the program to be doing.

So my question: Stop saving to a path using BinaryWriter, and start getting a byte[] I can use several times

This is the part where I think it saves to the given filepath.

string fullPath = C:/Users/Mathias/Documents/Lektier/IHA/3. Semester/Projekt/Temporary Blob + "/" + fileName;
        while (reader.Read())
        {
            FileStream fs = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.Write);
            BinaryWriter writer = new BinaryWriter(fs);
            CurrentIndex = 0;
            BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);
            while (BytesReturned == BufferSize)
            {
                writer.Write(Blob);
                writer.Flush();
                CurrentIndex += BufferSize;
                BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);
            }

            writer.Write(Blob, 0, (int)BytesReturned);

            writer.Flush(); writer.Close();
        }

My drawing skills are subpar

If you want the full source code for this form, please do ask. It's just kind of messy right now, so I didn't see the point of pasting the whole thing.

Upvotes: 2

Views: 1391

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500515

It sounds like you should just be writing to a MemoryStream:

var stream = new MemoryStream();
var buffer = new byte[8 * 1024];
long bytesRead;
long index = 0;
while ((bytesRead = reader.GetBytes(1, index, buffer, 0, buffer.Length)) > 0)
{
    stream.Write(buffer, 0, (int) bytesRead);
    currentIndex += bytesRead;
}
byte[] data = stream.ToArray();

Upvotes: 5

Related Questions