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

View: 4609|Reply: 1

[Source] .NET/C# Stream Read disk file memory optimization

[Copy link]
Posted on 6/9/2023 10:29:50 PM | | | |
Requirements: I wrote before that the file format is checked by the header of the file, actuallyYou only need to read the first few bytes of the file to judge, and you don't need to read the entire fileThis article uses Stream to read the first few bytes of a disk file and optimize memory space, which is actually what it isRead on demand

Review:

File size Bytes to KB, MB, GB, TB units intelligent conversion
https://www.itsvse.com/thread-3062-1-1.html

.NET/C# Uploads files based on byte[] in the file header
https://www.itsvse.com/thread-10594-1-1.html
useFile.ReadAllBytesReading the entire application file, you can see that the program is very occupied. As shown below:



In fact, it only takes 2 bytes to read to determine whether the file is an application or notStreamReaderRead the first 2 bytes of the file as shown below:

The hyperlink login is visible.



You can see from the original memoryReduced usage from 287.11 MB to 20.55 MB(Without reading the file, the default memory is taken up after the program starts: 20.02 MB), which shows that a lot of unnecessary memory expenses are saved. The code is as follows:

If we only want to see the beginning of the text, we can use the more command to view it, how to use .NET/C# code to read the text content?

It is read in two ways, and the code is as follows:



Since this file is plain text content,If it is UTF-8 or other encoding format, the first few bytes of the file need to be ignored, that is, the position of the stream needs to be set (e.g., Position = 2)

(End)





Previous:[MSSQL] SQL SERVER ordered GUIDs and unordered GUIDs as primary key aggregation index tests
Next:Insight: I saw a blogger's signature from the blog garden
 Landlord| Posted on 7/1/2023 9:13:08 PM |
Read the entire txt file

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