Friday, 30 June 2017

C# Split File

Hi all, here a very easy lwebcode free script to split file in C#

// calls example
...

int iSplittedFileSize = 1024 * 8;
SplitFile(@"C:\script\lwebcode.bak", iSplittedFileSize, @"C:\script\");

...

public static void SplitFile(string inputFile, int chunkSize, string path)
{
    const int BUFFER_SIZE = 20 * 1024; //2 Kb for each file
    byte[] buffer = new byte[BUFFER_SIZE];

    string baseFileName = Path.GetFileNameWithoutExtension(inputFile);
    string Extension = Path.GetExtension(inputFile);

    using (Stream input = File.OpenRead(inputFile))
    {
        int index = 0;
        while (input.Position < input.Length)
        {
            string sFinalName = path + "\\" + baseFileName + "." + index.ToString().PadLeft(5, Convert.ToChar("0")) + Extension + ".tmp";
            using (Stream output = File.Create(sFinalName))
            {
                int remaining = chunkSize, bytesRead;
                while (remaining > 0 && (bytesRead = input.Read(buffer, 0,
                        Math.Min(remaining, BUFFER_SIZE))) > 0)
                {
                    output.Write(buffer, 0, bytesRead);
                    remaining -= bytesRead;
                }
            }
            index++;
            System.Threading.Thread.Sleep(500);
        }
    }
}


Hope you like it ;)