473,549 Members | 3,127 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

One Byte Missing After Using FileStream

In the code below, I open a file using filestream, copy it to a byte
array, and the write that array out to a new file. But when I check
the size of the original file and the new file, the new file has one
less byte than the original file (although the file itself still works
fine). I was hoping someone could explain what is going on (why is
there a byte missing, and what might that byte be).

string originalFile = @"C:\MP3Test\Or iginal.mp3";
string copiedFile = @"C:\MP3Test\Co pied.mp3";

// Read file into byte array
FileStream fs1 = new FileStream(orig inalFile, FileMode.OpenOr Create,
FileAccess.Read );
byte[] mp3ByteArray = new byte[fs1.Length];
fs1.Read(mp3Byt eArray, 0, System.Convert. ToInt32(fs1.Len gth));
fs1.Close();

// Write same byte array to new file
int arraySize = new int();
arraySize = mp3ByteArray.Ge tUpperBound(0);
FileStream fs2 = new FileStream(copi edFile, FileMode.OpenOr Create,
FileAccess.Writ e);
fs2.Write(mp3By teArray, 0, arraySize);
fs2.Close();

// Compare size of original an new file
FileInfo fileInfo1 = new FileInfo(origin alFile);
FileInfo fileInfo2 = new FileInfo(copied File);

Console.WriteLi ne("Size of original file: " +
fileInfo1.Lengt h.ToString());
// output====> 20629 bytes
Console.WriteLi ne("Size of copied file: " +
fileInfo2.Lengt h.ToString());
// output====> 20628 bytes. One byte less than original file.

Thanks,

Terry

Nov 21 '05 #1
3 7300
Terry,

The reason you are getting this is because you are using a call to
GetUpperBound(0 ) on the array. This will return the index of the last
element in the array, which, in a zero-based array, turns out to be the
length - 1.

You can just do this:

int arraySize = mp3ByteArray.Le ngth;

And it will work out fine.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Terry" <te*******@yaho o.com> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
In the code below, I open a file using filestream, copy it to a byte
array, and the write that array out to a new file. But when I check
the size of the original file and the new file, the new file has one
less byte than the original file (although the file itself still works
fine). I was hoping someone could explain what is going on (why is
there a byte missing, and what might that byte be).

string originalFile = @"C:\MP3Test\Or iginal.mp3";
string copiedFile = @"C:\MP3Test\Co pied.mp3";

// Read file into byte array
FileStream fs1 = new FileStream(orig inalFile, FileMode.OpenOr Create,
FileAccess.Read );
byte[] mp3ByteArray = new byte[fs1.Length];
fs1.Read(mp3Byt eArray, 0, System.Convert. ToInt32(fs1.Len gth));
fs1.Close();

// Write same byte array to new file
int arraySize = new int();
arraySize = mp3ByteArray.Ge tUpperBound(0);
FileStream fs2 = new FileStream(copi edFile, FileMode.OpenOr Create,
FileAccess.Writ e);
fs2.Write(mp3By teArray, 0, arraySize);
fs2.Close();

// Compare size of original an new file
FileInfo fileInfo1 = new FileInfo(origin alFile);
FileInfo fileInfo2 = new FileInfo(copied File);

Console.WriteLi ne("Size of original file: " +
fileInfo1.Lengt h.ToString());
// output====> 20629 bytes
Console.WriteLi ne("Size of copied file: " +
fileInfo2.Lengt h.ToString());
// output====> 20628 bytes. One byte less than original file.

Thanks,

Terry

Nov 21 '05 #2
kids_pro <ki******@yahoo .com> wrote:
I am having the similiar problem.
But the different between the original file and the copy one is alot more.

int bufferSize = 102400;
byte[] read = new byte[bufferSize];

Stream fs = new
FileStream("E:\ \anders_hejlsbe rg_linq_2005.wm v",FileMode.Ope n);

Stream fs2 = new
FileStream("D:\ \anders_hejlsbe rg_linq_2005.wm v",FileMode.Cre ate);

int chunk=0;
while((chunk=fs .Read(read,0,bu fferSize))>0){
if(chunk < bufferSize){

/* truncate the byte it should reach end of file */
byte[] finalByte = new byte[chunk];
Array.Copy(read ,finalByte,chun k);
fs.Write(finalB yte,0,chunk);
}else{
fs2.Write(read, 0,bufferSize);
}

read = new byte[bufferSize];
}
fs.Close();
fs2.Close();

Please refer to attach screenshot for the size different.
Why the size is different? Have I done any mistakes?


Well, I'm not sure why you're copying the array in the case where you
haven't read the whole file in one go - just use
fs2.Write(read, 0, chunk)

However, the error in your program is that by introducing the extra
complexity, you've got your other Write call to the wrong stream -
you're writing to the stream you've been reading from!

Note that you should also use "using" statements to make sure that your
FileStreams get closed even if an exception is thrown.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #3
Thanks for the insights Nicholas and Jon. I'll spend some more time
studying this code and your responses so I understand it better.

This code was extracted from two methods I created to save .mp3's to a
database, and then write them out to a file again. I uncovered the
error when I wrote a unit test to compare the file before and after
saving to the database.

Thanks again.

Nov 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
13235
by: Andre Ranieri | last post by:
I'm having trouble programatically inserting an Excel file into an Image column in our CRM package's SQL 2000 database. The function appears to work ok, but when I attempt to access the file through the application's front end the file appears to be corrupt. The front-end application has a way of inserting files to the column, however when I...
9
1649
by: james | last post by:
I have a FileStream retrieved from FileOpenDialog. I have a Byte which I intend to store for later use. What is the most efficient way of getting the File into my Byte and tehn back out to a new FileStream ? I have been looking at all the Readers and Writers and due to information overload cannot decide on the proper method. Thanks, ...
1
15907
by: Greg Patrick | last post by:
My problem: I load an some assemblies (strong named) from a byte array using Assembly.Load(byte). They load fine. But one one of them is actually accessed, it's referenced assemblies can't be found on disk and I get a TargetInvocationExeption. For example, let's say I have a C# win forms application called Prog. Prog.exe uses...
1
3688
by: Marquee | last post by:
Hello, This is my first program c#, my background is c++. One thing I would like to do is put binary data (e.g. a record from disk, or network packet) in a struct. In C++ I would create the struct and memcpy() the data into it thus creating a structured overlay. The struct can have variable length e.g. struct CRecord //Just for example...
2
1858
by: Adam Clauss | last post by:
Alright, I have a webapp in which I need to send a byte (which happens to be the contents of an excel spreadsheet read in from the .xls file). Now, I can't actually redirect the user (Response.Redirect()) to the file, so I want to just send the byte itself. My question is, Response.Write() only takes a char, so how can I send this byte?...
4
16916
by: Gidi | last post by:
Hi, i have a byte array, and i'm writing it to a file, i want to start a new line, how can i do it? (like WriteLine in StreamWriter) I'm using FileStream: FileStream fs = new FileStream(file_name,FileMode.Create ); Aftrer i used fs.Write(Byte b1); i want to start a new line in my file and then write my second array Byte
8
4574
by: frekster | last post by:
Hi. I used to be able to do this easily in vb 6 via looping and preserving the source array data/size etc. How can I do this in vb.net? I've been trying for a while now and this should be an easy task but it just isn't clicking. For some reason, the preserve doesn't seem to be working.
5
2220
by: Pohihihi | last post by:
Hello All, While replying to my post many lost the track of what I was asking but it was nice to know few extra things. Well coming back to my problem -- My field is varbinary in SQL db. Do you think converting it into ToString() might create problem. "FullName" col is just an example, actually I am serializing a 3rd party control which...
4
2050
by: =?Utf-8?B?Unlhbg==?= | last post by:
How do I read a blob field of a database using System.Byte? A sample code would be appreciated.
0
7446
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7718
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7956
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6041
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5088
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3480
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.