473,788 Members | 2,816 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proper way to read a File to a Byte[] and vice versa

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,

JIM

Nov 16 '05 #1
9 1657
James,

It's quite simple. Assuming that you have a FileStream and it is
positioned at the first byte in the file, you can do this:

// Assume pobjStream is the filestream.
byte pbytBytes[] = new byte[pobjStream.Leng th];

// Read the bytes.
pobjStream.Read (pbytBytes, 0, pobjStream.Leng th);

That's really all there is to it. However, you have to be careful, for
large files, this can take up a huge chunk of memory. If it is possible to
process your file in smaller chunks, I would recommend doing that.

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

"james" <no****@hyperco n.net> wrote in message
news:uV******** *****@TK2MSFTNG P11.phx.gbl...
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,

JIM

Nov 16 '05 #2
Nick,

Thanks a lot, that should work. I guess I got caught up in all the Stream
classes and the Readers and Writers... that I missed the simple way to do
it. Also I was looking for a method like GetBytes or like GetBuffer that is
on MemoryStream to do it all in one go without having to specify ranges.

JIM
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:eE******** ******@TK2MSFTN GP09.phx.gbl...
James,

It's quite simple. Assuming that you have a FileStream and it is
positioned at the first byte in the file, you can do this:

// Assume pobjStream is the filestream.
byte pbytBytes[] = new byte[pobjStream.Leng th];

// Read the bytes.
pobjStream.Read (pbytBytes, 0, pobjStream.Leng th);

That's really all there is to it. However, you have to be careful, for large files, this can take up a huge chunk of memory. If it is possible to process your file in smaller chunks, I would recommend doing that.

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

"james" <no****@hyperco n.net> wrote in message
news:uV******** *****@TK2MSFTNG P11.phx.gbl...
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,

JIM


Nov 16 '05 #3
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard .caspershouse.c om> wrote:
It's quite simple. Assuming that you have a FileStream and it is
positioned at the first byte in the file, you can do this:

// Assume pobjStream is the filestream.
byte pbytBytes[] = new byte[pobjStream.Leng th];

// Read the bytes.
pobjStream.Read (pbytBytes, 0, pobjStream.Leng th);

That's really all there is to it. However, you have to be careful, for
large files, this can take up a huge chunk of memory. If it is possible to
process your file in smaller chunks, I would recommend doing that.


That's not quite all there is to it. Unless I've missed something,
FileStream.Read (like other streams) isn't guaranteed to return you all
the data you asked for in one lump. (Even if FileStream does guarantee
it, I wouldn't suggest relying on it - it's far too easy to get into
bad habits that way, and not notice when suddenly you're reading from a
NetworkStream instead of a FileStream, etc.)

See http://www.pobox.com/~skeet/csharp/readbinary.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
james <no****@hyperco n.net> wrote:
Thanks a lot, that should work. I guess I got caught up in all the Stream
classes and the Readers and Writers...


Readers and Writers are for when you want to convert binary to text or
vice versa. Streams are for binary data.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Jon,

Thanks for the warning, I am only expecting to be reading file streams, so I
could test for the Type and only procede if it is a file stream, but just to
clarify, in your example code at
http://www.pobox.com/~skeet/csharp/readbinary.html , is the first non safe
way (as Nick suggested) only non-safe when you are dealing with a non file
stream or could I run into troubl with File streams too ??

Thanks,

JIM

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard .caspershouse.c om> wrote:
It's quite simple. Assuming that you have a FileStream and it is
positioned at the first byte in the file, you can do this:

// Assume pobjStream is the filestream.
byte pbytBytes[] = new byte[pobjStream.Leng th];

// Read the bytes.
pobjStream.Read (pbytBytes, 0, pobjStream.Leng th);

That's really all there is to it. However, you have to be careful, for large files, this can take up a huge chunk of memory. If it is possible to process your file in smaller chunks, I would recommend doing that.


That's not quite all there is to it. Unless I've missed something,
FileStream.Read (like other streams) isn't guaranteed to return you all
the data you asked for in one lump. (Even if FileStream does guarantee
it, I wouldn't suggest relying on it - it's far too easy to get into
bad habits that way, and not notice when suddenly you're reading from a
NetworkStream instead of a FileStream, etc.)

See http://www.pobox.com/~skeet/csharp/readbinary.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #6
james <no****@hyperco n.net> wrote:
Thanks for the warning, I am only expecting to be reading file streams, so I
could test for the Type and only procede if it is a file stream, but just to
clarify, in your example code at
http://www.pobox.com/~skeet/csharp/readbinary.html , is the first non safe
way (as Nick suggested) only non-safe when you are dealing with a non file
stream or could I run into troubl with File streams too ??


I don't know for sure. The docs for FileStream.Read *suggest* that it
may not be safe, but my guess is that it will be for local files.

Why take the risk though? It's so easy to load it all reliably in a
single method call, why not use that?

If you're worried about the efficiency aspect, you could adapt the code
so that it didn't use a MemoryStream, but used a buffer it could return
directly, and which you'd expand/copy in the same way as MemoryStream
does. By creating it with a good size guess (eg using Stream.Length) to
start with, you may well be able to make things faster and less memory
hungry. Don't forget to trim the array if you end up with a buffer
which is larger than the actual data though...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7
Ok, thanks again. I'll use the safer way just in case

JIM
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
james <no****@hyperco n.net> wrote:
Thanks for the warning, I am only expecting to be reading file streams, so I could test for the Type and only procede if it is a file stream, but just to clarify, in your example code at
http://www.pobox.com/~skeet/csharp/readbinary.html , is the first non safe way (as Nick suggested) only non-safe when you are dealing with a non file stream or could I run into troubl with File streams too ??


I don't know for sure. The docs for FileStream.Read *suggest* that it
may not be safe, but my guess is that it will be for local files.

Why take the risk though? It's so easy to load it all reliably in a
single method call, why not use that?

If you're worried about the efficiency aspect, you could adapt the code
so that it didn't use a MemoryStream, but used a buffer it could return
directly, and which you'd expand/copy in the same way as MemoryStream
does. By creating it with a good size guess (eg using Stream.Length) to
start with, you may well be able to make things faster and less memory
hungry. Don't forget to trim the array if you end up with a buffer
which is larger than the actual data though...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #8
Jon,

I am using your ReadFully (NetworkStream stream) (as you can see i changed the parameter from Stream to NetworkStream). The problem i am having is when i am reading from the stream using the ReadFully method it seems like i am nor breaking out of the while loop.This occurs when i am sending the data into the stream from a telnet command window?(i am writing an smtp server and i am trying to test out with telneting to the ip and port with which my server is listening to)
Any suggestions would be appreciated.

Vinny
"Jon Skeet [C# MVP]" wrote:
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard .caspershouse.c om> wrote:
It's quite simple. Assuming that you have a FileStream and it is
positioned at the first byte in the file, you can do this:

// Assume pobjStream is the filestream.
byte pbytBytes[] = new byte[pobjStream.Leng th];

// Read the bytes.
pobjStream.Read (pbytBytes, 0, pobjStream.Leng th);

That's really all there is to it. However, you have to be careful, for
large files, this can take up a huge chunk of memory. If it is possible to
process your file in smaller chunks, I would recommend doing that.


That's not quite all there is to it. Unless I've missed something,
FileStream.Read (like other streams) isn't guaranteed to return you all
the data you asked for in one lump. (Even if FileStream does guarantee
it, I wouldn't suggest relying on it - it's far too easy to get into
bad habits that way, and not notice when suddenly you're reading from a
NetworkStream instead of a FileStream, etc.)

See http://www.pobox.com/~skeet/csharp/readbinary.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #9
<"=?Utf-8?B?VmlubnkgVml ubg==?=" <Vinny
Vi**@discussion s.microsoft.com>> wrote:
I am using your ReadFully (NetworkStream stream) (as you can see i
changed the parameter from Stream to NetworkStream). The problem i am
having is when i am reading from the stream using the ReadFully
method it seems like i am nor breaking out of the while loop.This
occurs when i am sending the data into the stream from a telnet
command window?(i am writing an smtp server and i am trying to test
out with telneting to the ip and port with which my server is
listening to)
Any suggestions would be appreciated.


Sure - the problem is that the server isn't terminating the connection,
so the stream is never finished. With a stream, there's no concept of
"finished this bit" which is what I think you want. You need to read
from the stream until the protocol itself tells you that this bit has
finished - for instance, with a dot on a line on its own, in many
protocols.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

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

Similar topics

17
10535
by: Guyon Morée | last post by:
what is the difference? if I open a text file in binary (rb) mode, it doesn't matter... the read() output is the same.
3
8477
by: mailar | last post by:
HI, Can anyone tell me how is a multi_byte to single byte and vice versa conversion done in DB2. It would be great even if someone can tell me how Oracle does it? Oracle already has functions called to_single_byte and to_multi_byte which convert a given multi byte character to single byte and vice versa respectively. thanks in advance mailar
289
1805
by: napi | last post by:
I think you would agree with me that a C compiler that directly produces Java Byte Code to be run on any JVM is something that is missing to software programmers so far. With such a tool one could stay with C and still be able to produce Java byte code for platform independent apps. Also, old programs (with some tweaking) could be re-compiled and ported to the JVM. We have been developing such a tool over the last 2 years and currently...
1
2533
by: Eugene Anthony | last post by:
Private Function BStr2UStr(BStr) 'Byte string to Unicode string conversion Dim lngLoop BStr2UStr = "" For lngLoop = 1 to LenB(BStr) BStr2UStr = BStr2UStr & Chr(AscB(MidB(BStr,lngLoop,1))) Next End Function Private Function UStr2Bstr(UStr)
18
1980
by: rdemyan via AccessMonster.com | last post by:
Here's my plan for creating nightly backups of the production back-end file (the IT staff in their infinite wisdom have prevented use of Windows Scheduler and users do not have administrative rights to Windows). Candace Tripp has an automatic backing up program that I modified for our use. You can schedule a time for the backup to occur. Since Windows task scheduler is not available to us, this means that the auto backup program will...
16
2155
by: Hugh Janus | last post by:
Hi all, I am using the below functions in order to convert strings to bytes and vice versa. I totally ans shamefully stole these functions from this group btw! Anyway, they work great but as sooooo slow. Anyone know how I can speed this functions up? I basically need to convert a byte to string, perform a function on each 'section' of the string, then reconvert it to a byte. The slow part is the conversion to and from byte, not the...
6
39289
yabansu
by: yabansu | last post by:
Hi all, I think most of you probably know the two .NET framework functions, namely Encoding.GetBytes(string) and Encoding.GetString(byte), to convert string into byte array and vice versa. Now, I want to do the same thing in pure(unmanaged) C++. I searched the Internet but could not find any satisfactory solutions. I am really in need of help! Is there anyone to explain how I can implement these functions by not using .NET library? ...
6
3502
by: Homer J. Simpson | last post by:
Hi all, I have enough experience with HTML/classic ASP to get by, and I'm trying to learn ASP.NET. Traditionally, I've taken the habit of breaking out extra-long CSS files into multiple, smaller ones, and referring to them in my HTML/ASP files on an as-needed basis. Essentially, I've organized things as: /default.asp
6
2258
by: Ole | last post by:
I have a class that I wish to convert into a byte array for sending over a serial line and vice versa - how do I do that? Thanks and regards Ole
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10172
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.