简体   繁体   中英

Create FileStream in memory instead of saving a physical file on disk

I am uploading a file to an api, and I have to copy my requestStream to a FileStream in order to post the file to the API. My code below works, but I have to save the file to a temp folder to create the FileStream, and then I have to clean up the temp folder again after the operation. Is there a cleaner way of doing that - eg creating the FileStream in memory (if that's possible) instead of saving it to the disk?

Stream requestStream = await Request.Content.ReadAsStreamAsync();

     //Create filestream by making a temporary physical file
     using (FileStream fileStream = System.IO.File.Create(@"C:\tempFolder\" fileName))                                     
     {
         await requestStream.CopyToAsync(fileStream);
         var postedFile = ms.CreateMedia(fileName, folder.Id, "file");                                    
         postedFile.SetValue("umbracoFile", fileName, fileStream);                                      
         ms.Save(postedFile);
     }

     // Clean up
     if ((System.IO.File.Exists(@"C:\tempFolder\" + fileName)))
     {
         System.IO.File.Delete(@"C:\tempFolder\" + fileName);
     }

Why not use the requestStream directly? It is an instance of Stream and your API end point expects an instance of Stream , there is no need to copy the content of requestStream to any intermediary point unless you want to add unnecessary overhead.

Stream requestStream = await Request.Content.ReadAsStreamAsync();

var postedFile = ms.CreateMedia(fileName, folder.Id, "file");
postedFile.SetValue("umbracoFile", fileName, requestStream);
ms.Save(postedFile);

.Net doesn't really provide a good in-memory solution. It is good to create your own to save resources and encapsulate more functionality.

Check out this guide here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM