3

We are getting a input from a web service as a byte[] (which we process internally) and we need to upload to another web service which accepts only a file stream.

How can i to convert byte[] to a file stream without writing to disk in C#?


Edit: This is not duplicate. I am not asking how to convert byte[] to memory stream or file steam. I am asking how to convert byte[] to file stream without writing to disk. Please note that, I need to send the data as file steam to a third party web service, which I do not have access. This web service accepts only as file stream.

So far I have below code:

string fileWritePath = "c:\\temp\\test.docx";
//here fileContent is a byte[]
File.WriteAllBytes(fileWritePath, fileContent);
FileStream fileStream = new FileStream(fileWritePath, FileMode.Open, FileAccess.Read);

I do not want to write the file to local disk and create file stream.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
CSS
  • 154
  • 1
  • 2
  • 12
  • Create `MemoryStream` and "store" the byte[] array into it. – i486 Dec 20 '16 at 14:08
  • 3
    An external _web_ service accepts a _file_ stream? That doesn't seem to be possible. A file stream is on your disc and the web service is accessible through a network. These are two entirely different things. – Sefe Dec 21 '16 at 08:31
  • I agree with @Sefe .Roughly speaking, a `FileStream`is a wrapper on an handle for a resource (a file on the disk usually). this handle has a meaning only locally, on the computer where you create the FileStream. When you pass this object to an external web server, the underlying handle will not have any meaning. – Gian Paolo Dec 21 '16 at 08:55
  • @css How can a web service only except FileStream? How do you access this service? – Magnus Feb 27 '19 at 10:51

2 Answers2

4

Use MemoryStream:

using(var stream = new MemoryStream(byteArray)){
   SendStreamToService(stream);
}
Keith
  • 150,284
  • 78
  • 298
  • 434
0

If you are bound to a file stream, you have to use it. If you don't want to go through a physical hard drive you can install a ram disc on your system that maps parts of the memory to a virtual drive and use this drive to map your FileStream to.

Sefe
  • 13,731
  • 5
  • 42
  • 55
  • see my comment above original post: even if you use a ram disk, I think the FileStream cannot work when you transfer it over a network – Gian Paolo Dec 21 '16 at 08:57
  • @GianPaolo: Maybe OP _says_ web service, but _means_ something else. – Sefe Dec 21 '16 at 09:45