File and byte [] interchange in C #

Source: Internet
Author: User

[Question]: How can I convert images and sounds into byte [] and transmit them through webservice?
How can we convert byte [] transmitted by webservice into the desired file?
(1) converting a file to byte []
Method 1: Use MemoryStream (the data of MemoryStream comes from the memory buffer)
System. IO. MemoryStream m = new System. IO. MemoryStream ();
System. Drawing. Bitmap bp = new System. Drawing. Bitmap (pname );
Bp. Save (m, System. Drawing. Imaging. ImageFormat. Jpeg); // Save the image to the specified stream in the specified format.
Byte [] B = m. GetBuffer (); // read from memory buffer
Method 2: Use FileStream (the data of the FileStream object comes from the file)
FileStream stream = new FileInfo (path). OpenRead ();
Byte [] buffer = new Byte [stream. Length];
// Read the byte block from the stream and write the data into the given buffer.
Stream. Read (buffer, 0, Convert. ToInt32 (stream. Length ));
(2) Converting byte [] into a file
WebReference. MyService obj = new WebReference. MyService ();
Byte [] B = obj. downWav ("1001"); // 1001 pid of a record, returns the byte of the image in this record []
MemoryStream m = new MemoryStream (B );
String file = string. Format (@ "%0%e.wav ",
Path. GetDirectoryName (Assembly. GetExecutingAssembly (). GetName (). CodeBase ));
// Save the downloaded file in the current directory as e.wave. Of course, if the image is used, save it as a.jpg.
FileStream fs = new FileStream (file, FileMode. OpenOrCreate );
M. WriteTo (fs );
M. Close ();
Fs. Close ();
M = null;
Fs = null;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.