My files Shrink by half!!!

E

Ebrahim

I am trying to copy a file using BinaryReader / Writer .
I started with this mp3 .. it was ~640 kb . BUt THe output file that
is created by my code is only ~320 kb ??

heres the code

--------------------------------------------------------------------------------

try
{
//System.Net.Sockets.TcpClient t = new
System.Net.Sockets.TcpClient("localhost",15000);

//BinaryWriter outs = new BinaryWriter(t.GetStream());

BinaryReader fs = new
BinaryReader((Stream)File.Open(@"c:\\dumb.mp3",FileMode.Open));

BinaryWriter outf = new
BinaryWriter((Stream)File.Open(@"c:\dummy.mp3",FileMode.OpenOrCreate,FileAccess.Write));

byte [] cbuf = new byte[1024];
this.progressBar1.Minimum = 0;
this.progressBar1.Maximum = 100;

MessageBox.Show(fs.BaseStream.Length.ToString());
while(fs.BaseStream.Position < fs.BaseStream.Length)
{
fs.Read(cbuf , 0 , 1024);
fs.BaseStream.Position+=1024;

outf.Write(cbuf,0,cbuf.Length);
//outf.Flush();

this.progressBar1.Value =
(int)(fs.BaseStream.Position/fs.BaseStream.Length)*100;
//outs.Write(cbuf,0,1024);
Application.DoEvents();


}

outf.Flush();
fs.Close();
outf.Close();//outs.Close();
//t.Close();

}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
 
J

Jon Skeet [C# MVP]

Ebrahim said:
I am trying to copy a file using BinaryReader / Writer .
I started with this mp3 .. it was ~640 kb . BUt THe output file that
is created by my code is only ~320 kb ??

These lines are the main problem:

fs.Read(cbuf , 0 , 1024);
fs.BaseStream.Position+=1024;

You're reading a kilobyte, and then *skipping* a kilobyte. You're also
always assuming that you've managed to read a whole kilobyte - you're
ignoring the return value of BinaryReader.Read. Furthermore, you're
assuming that no buffering is taking place, when it might be - this
would cause you to stop reading too early.


Here's a much simpler and more robust way of working:

static void CopyStream (Stream input, Stream output)
{
byte[] buffer = new byte[16384];

int read;

while ( (read=input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}

You'd then call it with:

using (Stream input = File.Open ("c:\\dumb.mp3", FileMode.Open))
{
using (Stream output = File.Open ("c:\\dummy.mp3",
FileMode.OpenOrCreate, FileAccess.Write))
{
CopyStream (input, output);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top