Search code examples
c#arrayssystem.io.file

How to rewrite file as byte array fast C#


Hello I am trying to rewrite file by replacing bytes but it takes too much time to rewrite large files. For example on 700MB this code was working about 6 minutes. Pls help me to make it work less than 1 minute.

static private void _12_56(string fileName)
{
    byte[] byteArray = File.ReadAllBytes(fileName);
    for (int i = 0; i < byteArray.Count() - 6; i += 6)
    {
        Swap(ref byteArray[i], ref byteArray[i + 4]);
        Swap(ref byteArray[i + 1], ref byteArray[i + 5]);
    }
    File.WriteAllBytes(fileName, byteArray);
}

Solution

  • As the other answer says, you have to read the file in chunks.

    Since you are rewriting the same file, it's easiest to use the same stream for reading and writing.

    using(var file = File.Open(path, FileMode.Open, FileAccess.ReadWrite)) {        
        // Read buffer. Size must be divisible by 6
        var buffer = new byte[6*1000]; 
    
        // Keep track of how much we've read in each iteration
        var bytesRead = 0;      
    
        // Fill the buffer. Put the number of bytes into 'bytesRead'.
        // Stop looping if we read less than 6 bytes.
        // EOF will be signalled by Read returning -1.
        while ((bytesRead = file.Read(buffer, 0, buffer.Length)) >= 6)
        {   
            // Swap the bytes in the current buffer
            for (int i = 0; i < bytesRead; i += 6)
            {
                Swap(ref buffer[i], ref buffer[i + 4]);
                Swap(ref buffer[i + 1], ref buffer[i + 5]);
            }
    
            // Step back in the file, to where we filled the buffer from
            file.Position -= bytesRead;
            // Overwrite with the swapped bytes
            file.Write(buffer, 0, bytesRead);
        }
    }