V
V
vladimirchelyabinskiy2016-04-29 08:13:34
C++ / C#
vladimirchelyabinskiy, 2016-04-29 08:13:34

C# How to read from file, first 1000 bytes into byte array?

Good afternoon
There is a code which reads out all file.

public static void SelectFile(string file)
        {
            byte[] bytesToBeEdit = File.ReadAllBytes(file);
            // Тут_творим_с(файлом, чтохотим);
        }

I need to read the first 1000 bytes of a file and write it to a byte array (bytesToBeEdit)
How can I do this?
In general, it is desirable to somehow organize a check before loading (the number of bytes in the file)
Next, take 10% of the number of bytes and write them to an array (bytesToBeEdit)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maa-Kut, 2016-04-29
@vladimirchelyabinskiy

byte[] bytes = new byte[1000];
using(var stream = File.OpenRead(fileName))
{
    int count = stream.Read(bytes, 0, 1000);
}

If you need 10% straight, then a little more complicated:
var fileInfo = new FileInfo(fileName);
int chunkSize = fileInfo.Length / 10;
byte[] bytes = new byte[chunkSize];

using(var stream = fileInfo.OpenRead())
{
    int count = stream.Read(bytes, 0, bytes.Length);
}

V
Vyacheslav, 2016-04-29
@Firik67

https://msdn.microsoft.com/en-us/library/system.io...
In the example below, everything is there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question