Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use C # to read files more efficiently

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to use C# to read files is more efficient, I believe that most people do not understand, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Usually we use C# to read a file using the following steps:

1. Declare and instantiate a file stream object using File's OpenRead, like this

FileStream fs = File.OpenRead (filename)

Or

FileStream fs = FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read)

2. Prepare a byte array to store the contents of the file, and fs.Length will get the actual size of the file, like the following

Byte [] data = new byte [fs.Length]

3. Wow! Start to read, call a method of a file stream to read the data into the data array

Fs.Read (data, 0, data.Length)

It is so concise that we can read out the contents of the document intact after only 3 sentences. Can this code really work as you expected? The answer is: almost yes! The above code works well in most cases, but we should note that the Read method has a return value, and since there is a return value, it must make sense, if written as above, it can be a function with no return value. I think the purpose of the return value is to give us a chance to determine the size of the actual read file, and thus to determine whether the file has been fully read. So the above code does not guarantee that we have read all the bytes in the file (although in many cases we have). The following method provides a more secure method than the one above to ensure that the file is fully read

Public static void SafeRead (Stream stream, byte [] data) {int offset=0; int remaining = data.Length; / / keep reading while (remaining > 0) {int read = stream.Read (data, offset, remaining) as long as there are remaining bytes; if (read)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report