简体   繁体   English

如何从字节数组创建文件并将其作为文件发送到流中,而无需在磁盘上创建此文件?

[英]How can I create a file from a byte array and send it to the stream as a file without creating this file on the disk?

是否可以从字节数组创建文件并将其作为文件直接发送到流,而无需在磁盘上创建此文件?

There is a MemoryStream class that takes a byteArray as argument.有一个将 byteArray 作为参数的MemoryStream类。 You don't need to write a file.你不需要写文件。

Stream stream = new MemoryStream(byteArray);

Alternatively, you can Write to an existing MemoryStream :或者,您可以Write现有的MemoryStream

memStream.Write(byteArray, 0 , byteArray.Length);

Your question is not very clear.你的问题不是很清楚。 You are asking to "create a file" and yet you are saying "without creating this file on disk".您要求“创建文件”,但您说的是“不在磁盘上创建此文件”。 However it is possible to either "create a file from a byte array" :但是,可以“从字节数组创建文件”:

File.WriteAllBytes( path, bytes );

where path is the filename to create and bytes is the byte[] to write - this is just one of those many ways.其中 path 是要创建的文件名, bytes 是要写入的 byte[] - 这只是众多方式中的一种。

Or "send to a stream without creating file on disk".或者“发送到流而不在磁盘上创建文件”。 ie: Write to MemoryStream:即:写入 MemoryStream:

var ms = new MemoryStream( bytes );

I am afraid your question needs to be more specific on what you are trying to do.恐怕您的问题需要更具体地说明您要做什么。

Edit: Crypto sample:编辑:加密示例:

private static byte[] Crypt
  (byte[] data, byte[] key, byte[] iv, ICryptoTransform cryptor)
{
  MemoryStream m = new MemoryStream();
  using( Stream c = new CryptoStream(m, cryptor, CryptoStreamMode.Write ))
  {
    c.Write(data, 0, data.Length);
  }
  return m.ToArray();
}

public static byte[] Encrpyt(byte[] data, byte[] key, byte[] iv)
{
  using( Aes algorithm = Aes.Create())
  using( ICryptoTransform encryptor = algorithm.CreateEncryptor(key,iv))
  {
    return Crypt( data, key, iv, encryptor );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何压缩目录然后返回生成的字节数组,而无需在磁盘上物理创建 zip 文件? - How can I compress a Directory then return the resulting byte array, without physically creating zip file on disk? 将byte []转换为文件流而无需写入磁盘 - Convert byte[] to file stream without writing to disk 如何从字节数组创建文件并将其发送到 TelegramBot - How to create file from byte array and send it to TelegramBot 如何在不使用磁盘且内存不足的情况下将大型文件从api流式传输到api? - How do I stream a large file from api to api without using disk and running out of memory? 如何从字节中的音频文件创建AudioClip [] - How can I create an AudioClip from an audio file in byte[] 从字节数组或流中获取文件名 - Get file name from byte array or Stream 从 memory 中的.zip 文件中获取字节数组,无需向磁盘写入任何内容 - Get byte array from .zip file in memory, without writing anything to disk 从字节数组中获取要作为附件发送的文件 - Get file to send as attachment from byte array 如何在C#中创建,编写然后返回文件而不将其保存到磁盘 - How can I Create, write and then return a file in C# without saving it to disk 使用流创建文本文件,但不写入磁盘 - Creating text file using stream but not writing to disk
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM