-2

I'm getting a request from my front end to get the file.

So I have a byte array saved in my SQL DB, I it looks like to use File result I need to return a FileStream converted from the byte array.

I tried following MSDN to do this, using my byte array I get from my DB, but I get an error on the line

using(FileStream fileStream = new FileStream(fileName, FileMode.Create))
{

Access to the path 'C:\Program Files (x86)\IIS Express\Test.docx' is denied.

Obviously, I know what's happening. It's using the fileName as path to find a file instead of creating a new file. Why is this happening? How do I return my byte array as a file in a FileStream? Should I even write file to disk if I need to return it in response?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Jun Kang
  • 1,267
  • 1
  • 10
  • 27
  • 1
    Its not about the FileStream or bytes - read the error message. You cannot do File IO to that folder and has been that way for many years. – Ňɏssa Pøngjǣrdenlarp Feb 05 '18 at 18:17
  • Run visual studio as Administrator – Elham Kohestani Feb 05 '18 at 18:22
  • I've edited the question as it looks like you are talking about some sort of WebServer returning a file response. Feel free to revert if this is not correct interpretation of the question. I used MVC version as duplicate, but if you need ASP one - https://stackoverflow.com/questions/14935205/retrieve-image-from-database-in-asp-net. – Alexei Levenkov Feb 05 '18 at 18:27

1 Answers1

2

FileStream is for dealing with files on disk. It would be inefficent to save the file to disk, then re-read it and return that to the user. Use a MemoryStream which takes a byte[].

Since it sounds like you are using ASP.NET MVC, you can also just call File with your byte[].

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • So in which case would `FileStream`'s [WriteByte](https://msdn.microsoft.com/en-us/library/system.io.filestream.writebyte(v=vs.110).aspx) be used? The `WriteByte` documentation, at least for me, seems to suggest it would be used in the case I thought because of the following line: "`The following code example shows how to write data to a file, byte by byte`". But obviously I misinterpreted that. – Jun Kang Feb 05 '18 at 20:15
  • @JunKang its used when you want to write a single byte to disk. – Daniel A. White Feb 05 '18 at 20:27