Thứ Hai, 19 tháng 8, 2019

Split & Merge C#

protected void btnSplit_Click(object sender, EventArgs e)
    {
        string inputFile = @"E:\TEST\BQDH.mp4"; // Input File
        int numberOfFiles = 2; // cắt ra 2 file

        FileStream fs = new FileStream(inputFile, FileMode.Open, FileAccess.Read);

        int sizeOfEachFile = (int)Math.Ceiling((double)fs.Length / numberOfFiles);

        for (int i = 1; i <= numberOfFiles; i++)
        {
            string baseFileName = Path.GetFileNameWithoutExtension(inputFile);
            string extension = Path.GetExtension(inputFile);
            FileStream outputFile = new FileStream(Path.GetDirectoryName(inputFile) + "\\" + baseFileName + "." + i.ToString().PadLeft(5, Convert.ToChar("0")) + extension + ".tmp", FileMode.Create, FileAccess.Write);
            int bytesRead = 0;
            byte[] buffer = new byte[sizeOfEachFile];

            if ((bytesRead = fs.Read(buffer, 0, sizeOfEachFile)) > 0)
            {
                outputFile.Write(buffer, 0, bytesRead);
            }
            outputFile.Close();
        }
        fs.Close();
    }
    protected void btnMerge_Click(object sender, EventArgs e)
    {
        string inPath = @"E:\TEST\"; // Input Folder
        string outPath = @"E:\TEST\output\"; // Output Folder

        string[] tmpFiles = Directory.GetFiles(inPath, "*.tmp");
        FileStream outputFile = null;
        string prevFileName = "";

        foreach (string tempFile in tmpFiles)
        {

            string fileName = Path.GetFileNameWithoutExtension(tempFile);
            string baseFileName = fileName.Substring(0, fileName.IndexOf(Convert.ToChar(".")));
            string extension = Path.GetExtension(fileName);

            if (!prevFileName.Equals(baseFileName))
            {
                if (outputFile != null)
                {
                    outputFile.Flush();
                    outputFile.Close();
                }

                String mergerPath = outPath + baseFileName + extension;

                outputFile = new FileStream(mergerPath, FileMode.OpenOrCreate, FileAccess.Write);
            }

            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            FileStream inputTempFile = new FileStream(tempFile, FileMode.OpenOrCreate, FileAccess.Read);

            while ((bytesRead = inputTempFile.Read(buffer, 0, 1024)) > 0)
                outputFile.Write(buffer, 0, bytesRead);

            inputTempFile.Close();
            File.Delete(tempFile);
            prevFileName = baseFileName;
        }
        outputFile.Close();
    }

Không có nhận xét nào:

Đăng nhận xét