Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace SlicingFile
- {
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- public class SlicingFile
- {
- public static void Main()
- {
- const string SourceFilePath = @"../../source.mp4";
- const string DestinationFolder = @"../../Slices";
- Console.Write("Enter the number of slices: ");
- int numberOfSlices = int.Parse(Console.ReadLine());
- Slice(SourceFilePath, DestinationFolder, numberOfSlices);
- List<string> fileNames = Directory.GetFiles(DestinationFolder).ToList();
- Assemble(fileNames, "../../");
- }
- private static void Slice(string sourceFilePath, string destinationDirectory, int numberOfSlices)
- {
- using (var source = new FileStream(sourceFilePath, FileMode.Open))
- {
- int bytesPerFile = (int)(source.Length / numberOfSlices);
- int remainingBytes = (int)(source.Length % numberOfSlices);
- string fileExtension = Path.GetExtension(source.Name);
- for (int fileIndex = 0; fileIndex < numberOfSlices; fileIndex++)
- {
- string fileName = string.Format("File-{0}{1}", fileIndex, fileExtension);
- string destinationPath = destinationDirectory + "/" + fileName;
- var bytesToWrite = fileIndex == numberOfSlices - 1 ? remainingBytes : bytesPerFile;
- byte[] buffer = new byte[bytesToWrite];
- using (var destination = new FileStream(destinationPath, FileMode.Create))
- {
- source.Read(buffer, 0, bytesToWrite);
- destination.Write(buffer, 0, bytesToWrite);
- }
- }
- }
- }
- private static void Assemble(List<string> files, string destinationDirectory)
- {
- const int DefaultBufferSizeInBytes = 4096;
- string extension = files[0].Substring(files[0].LastIndexOf('.'));
- string path = destinationDirectory + "assembled" + extension;
- using (var assembled = new FileStream(path, FileMode.Append, FileAccess.Write))
- {
- byte[] buffer = new byte[DefaultBufferSizeInBytes];
- foreach (var file in files)
- {
- using (var slice = new FileStream(file, FileMode.Open))
- {
- while (true)
- {
- int bytesRead = slice.Read(buffer, 0, DefaultBufferSizeInBytes);
- if (bytesRead == 0)
- {
- break;
- }
- assembled.Write(buffer, 0, bytesRead);
- }
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement