This article is a mirror article of machine translation, please click here to jump to the original article.

View: 38466|Reply: 0

[Tips] How to save a stream to a file in C#/.NET

[Copy link]
Posted on 2021-5-16 21:12:58 | | |
Looked at some blog posts online about saving Stream to a file,Many are incorrect。 (I found several problems: poor performance, abnormal when the stream is too large)

After getting a Stream how to elegantly save this Stream to code

The most elegant method should be through the method of CopyTo or CopyToAsync


here inputStream.Seek(0, SeekOrigin.Begin); Not necessarily, please use this code according to your own needs, such as you only need to copy the stream from the 10th byte, etc

Using the asynchronous approach will take a little longer for this write, but it will give the overall performance better and allow the CPU to handle other tasks




Note that when using CopyToAsync, remember to add await, when executing this code, you will hand over the execution to IO, most IO processing does not require CPU to compute, so that the overall performance can be better

Also, if the iputStream is coming in from outside, then I don't recommend releasing it inside this method, why? I used a good stream and it was killed when I passed in a business

The second method is to control the memory replication cache yourself, which will have an additional memory copy


What this method does is allow you to modify the value of new byte[1024], giving you control over the copied cache

The next are some methods that are not recommended, but they are convenient when writing


The above method will copy the memory twice, and if the input resource length is 1G, it will occupy 2G of resources

Similar to the above is to request a large cache, as shown in the following code


In terms of efficiency and code elegance, they are actually inferior to the CopyTo method, and because of stream. Length as length does not determine the cache, so it is not as good as the second method

Below is a super slow method, one byte by one byte writing is super slow


Transferred from:The hyperlink login is visible.
(End)




Previous:NPOI Operation Excel Detailed Explanation
Next:X-Forwarded-For multiple IP addresses in the HTTP request header
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com