File splitter Learn programming Visual Basic (VB.net)



Lesson:

File Management


Exercise:

File splitter


Objetive:

Create a program to split a file (of any kind) into pieces of a certain size. It must receive the name of the file and the size as parameters. For example, it can be used by typing:

split myFile.exe 2000

If the file "myFile.exe" is 4500 bytes long, that command would produce a file named "myFile.exe.001" that is 2000 bytes long, another file named "myFile.exe.002" that is also 2000 bytes long, and a third file named "myFile.exe.003" that is 500 bytes long.


Code:

Imports System
Imports System.IO
Public Class splitFile
    Public Shared Sub Main(ByVal args As String())
        Dim myFile As FileStream
        Dim myNewFile As FileStream
        Dim nameFile As String
        Dim BUFFER_SIZE As Integer
        Dim amountRead As Integer
        Dim count As Integer = 1

        If args.Length = 2 Then
            nameFile = args(0)
            BUFFER_SIZE = Convert.ToInt32(args(1))
            Dim data As Byte() = New Byte(BUFFER_SIZE - 1) {}

            Try
                myFile = File.OpenRead(nameFile)

                Do
                    amountRead = myFile.Read(data, 0, BUFFER_SIZE)
                    myNewFile = File.Create(nameFile & count.ToString("000"))
                    myNewFile.Write(data, 0, amountRead)
                    count += 1
                    myNewFile.Close()
                Loop While amountRead = BUFFER_SIZE

                myFile.Close()
            Catch fileError As Exception
                Console.WriteLine("ERROR has ocurred while executing: " & fileError.Message)
            End Try
        Else
            Console.WriteLine("The parameters are incorrects")
            Console.WriteLine("usage: splitfile namefile sizeinbytes")
        End If
    End Sub
End Class



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.