获取字节数组而不是将字节数组保存为文件

时间:2013-11-19 17:06:36

标签: c# arrays bytearray storage

我从SQL服务器获取原始varbinary数据。 首先我将其保存为文件,因为我正在加载文件并在图表上绘制一系列点。但是现在我还想在用户点击按钮时将其保存到另一台服务器。 这非常愚蠢:

  1. 从服务器加载二进制数据
  2. '转换'为文件
  3. 将其保存到路径
  4. 从此路径加载。
  5. 绘制图表。
  6. 从此路径加载
  7. 保存到服务器。
  8. 当我可以做的时候:

    1. 从服务器加载二进制数据
    2. '转换'为Byte []或其他类型的数组。
    3. 从此阵列中绘制图表
    4. 将此阵列保存到服务器。
    5. 我认为它需要是一个字节数组,因为我正在加载的服务器和我保存的服务器具有数据类型varbinary(max)。我附上了一份关于我希望该计划正在做什么的图片。

      所以我的问题:使用BinaryWriter停止保存到路径,并开始获取一个字节[]我可以多次使用

      这是我认为它保存到给定文件路径的部分。

      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

      如果您需要此表单的完整源代码,请询问。现在它只是一种混乱,所以我没有看到粘贴整个事情的重点。

1 个答案:

答案 0 :(得分:5)

听起来你应该写一个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();
相关问题