elena1234

Slice a file to equal parts- with buffer and stream

Jan 15th, 2021 (edited)
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.79 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4.  
  5. namespace SliceAFile
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             using var readerInput= new FileStream("input.txt", FileMode.Open); // open a FileStream
  12.             var parts = 4;
  13.             var length = (int)Math.Ceiling((decimal)readerInput.Length / parts);
  14.             var buffer = new byte[length];
  15.            
  16.             for (int i = 0; i < parts; i++)
  17.             {
  18.                 var bytesRead = readerInput.Read(buffer, 0, buffer.Length); // read the current bytes
  19.                 using var writer = new FileStream($"Part-{i + 1}.txt", FileMode.Open); // open a FileStream
  20.                 writer.Write(buffer, 0, bytesRead); // write in a file
  21.             }
  22.         }
  23.     }
  24. }
  25.  
Add Comment
Please, Sign In to add comment