【问题标题】:Getting a byte array instead of saving a byte array as a file获取字节数组而不是将字节数组保存为文件
【发布时间】:2013-11-19 17:06:36
【问题描述】:

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

  1. 从服务器加载二进制数据
  2. “转换”为文件
  3. 保存到路径
  4. 从此路径加载。
  5. 绘制图表。
  6. 从此路径加载
  7. 保存到服务器。

什么时候可以做:

  1. 从服务器加载二进制数据
  2. “转换”为 Byte[] 或其他类型的数组。
  3. 从此数组中绘制图表
  4. 将此数组保存到服务器。

我认为它需要是一个字节数组,因为我从中加载的服务器和我保存到的服务器具有数据类型 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();
        }

如果您想要此表单的完整源代码,请询问。现在有点乱,所以我没有看到粘贴整个东西的意义。

【问题讨论】:

  • 重要的是,无论您用来绘制图表的任何内容,都可以接受文件名以外的其他参数...
  • 呵呵,确实如此。我将 byte[] 转换为字符串,然后为其中的每一行拆分字符串('\n')然后我将它存储在一个字符串数组中,并为该字符串 [] 中的每个字符串运行一个 foreach 并添加一个点到一个系列。

标签: c# arrays bytearray storage


【解决方案1】:

听起来你应该写信给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();

【讨论】:

  • 这看起来很对!我正在尝试这段代码,我在 while 循环中得到它;不存在数据时尝试读取无效。我选择了正确的列,并且肯定存在数据。我的读者:SqlDataReader reader = LoadCmd.ExecuteReader(CommandBehavior.SequentialAccess);我的命令:SqlCommand LoadCmd = new SqlCommand("Select ekgmaaleid,raa_data,borger_fornavn,borger_efternavn,borger_beskrivelse,borger_cprnr,dato,maaleformat_type,fil_navn from EKG_Temp where fil_navn = @fil_navn", GlobalVariables.con);
  • 哈哈傻。我从来没有让读者真正阅读。解决了。谢谢你,朋友。
猜你喜欢
  • 2021-05-25
  • 2012-10-24
  • 1970-01-01
  • 2013-10-18
  • 2013-10-19
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
相关资源
最近更新 更多