karthik
karthik

Reputation: 4735

Problem in splitting a file

int bufferlength = 12488;
int pointer = 1;
int offset = 0;
int length = 0;

FileStream fstwrite = new FileStream("D:\\Movie.wmv", FileMode.Create);
while (pointer != 0)
{
    byte[] buff = new byte[bufferlength];
    FileStream fst = new FileStream("E:\\Movie.wmv", FileMode.Open);
    pointer = fst.Read(buff, 0, bufferlength);
    fst.Close();
    fstwrite.Write(buff, offset , pointer);
    offset += pointer;
}

I used the above code for splitting a file and place it in other drive.Im not able to set the correct offset and length for this routine can anyone help me to fix this

splitting in the sense ,i split it in "x" kbs and pass it somewhere make the same file in some other location

I find it atlast ,thanks to evry one who gave their valueble responses.

Upvotes: 0

Views: 190

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500855

Currently you're always reading from the start of the file... and even if you weren't you'd just be copying the whole file.

Here's some code which will actually split a single file into multiple files:

public static void SplitFile(string inputFile,
                             string outputPrefix,
                             int chunkSize)
{
    byte[] buffer = new byte[chunkSize];
    using (Stream input = File.OpenRead(inputFile))
    {
        int index = 0;
        while (input.Position < input.Length)
        {
            using (Stream output = File.Create(outputPrefix + index))
            {
                int chunkBytesRead = 0;
                while (chunkBytesRead < chunkSize)
                {
                    int bytesRead = input.Read(buffer, 
                                               chunkBytesRead, 
                                               chunkSize - chunkBytesRead);
                    // End of input
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    chunkBytesRead += bytesRead;
                }
                output.Write(buffer, 0, chunkBytesRead);
            }
            index++;
        }
    }
}

Upvotes: 6

cjk
cjk

Reputation: 46425

Don't open your source file inside the loop, or you'll always read the first chunk.

Open it before the loop, then make sure your offset is applied to the read.

Upvotes: 1

RvdK
RvdK

Reputation: 19790

Your reading bufferlength of bytes. Shouldn't you set the offset like this then?

offset += bufferlength;

Upvotes: 2

Related Questions