473,512 Members | 15,089 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

write byte trouble

Krantor
4 New Member
Hi all,

i am quite new to c# and was wondering if i could get assistance on an issue im having with writing a binary file from the database to my local machine, this is the code i have:

Expand|Select|Wrap|Line Numbers
  1. string inputString = Convert.ToString(reader["Attachment"]);
  2.  
  3.                         byte[] AttachmentByte;
  4.                         AttachmentByte = StringToByteArray(inputString);
  5.  
  6.                         string dir = "";
  7.                         dir = reader["Attachment"].ToString();
  8.                         string FilePath = dir;
  9.  
  10.                         // Specify a "currently active folder"
  11.                         string activeDir = @"C:\Documents and Settings";
  12.                         //Create a new subfolder under the current active folder
  13.                         string newPath = System.IO.Path.Combine(activeDir, "PDF Attachments");
  14.                         // Create a new file name.
  15.                         string newFileName = "Attachments.pdf";
  16.                         // Combine the new file name with the path
  17.                         newPath = System.IO.Path.Combine(activeDir, newFileName);
  18.                         // Create the file and write to it.
  19.                         // REMEMBER: System.IO.File.Create will overwrite the file if it already exists.
  20.                         //if (!System.IO.File.Exists(newPath))
  21.                         //{
  22.                             using (System.IO.FileStream fs = System.IO.File.Create(newPath))
  23.                             {
  24.                                 for (byte i = 0; i < 100; i++)
  25.                                 {
  26.                                     fs.Write(AttachmentByte, 0, AttachmentByte.Length);
  27.                                 }
  28.                             }
and the function for converting the string to a byte:

Expand|Select|Wrap|Line Numbers
  1. public static byte[] StringToByteArray(string inputString)
  2.     {
  3.         System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  4.         return encoding.GetBytes(inputString);
  5.     }
the problem is that the file is 230kb, but when i write it the i only get 2kb.

is there something i am doing wrong?
Dec 11 '08 #1
1 1774
nukefusion
221 Recognized Expert New Member
If I was going to store a binary file within a database field I would probably open the reader in SequentialAccess mode, use the SqlDataReader.GetBytes() method to retrieve the binary data into a buffer and a BinaryWriter object to write it down to the file stream. I've done this a couple of times before, albeit some time ago.

You may have better results going down that route as when attempting to convert binary to strings and back again you can come across all sorts of encoding issues.

You also seem to have something weird going on there with your FOR loop - the iteration seems unneccesary. I've cobbled together a rough code sample to give you an idea of what I mean, although be warned I haven't had time to test it, however it should give you an idea of how to go about it.

Expand|Select|Wrap|Line Numbers
  1. SqlCommand command = new SqlCommand("SELECT Attachment FROM MyDBTable WHERE ID = 1", myConnection);
  2. SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
  3. while (reader.Read())
  4. {
  5.     FileStream fileStream = new FileStream("myBinaryFile.dat", FileMode.OpenOrCreate, FileAccess.Write);
  6.     BinaryWriter binaryWriter = new BinaryWriter(fileStream);
  7.     long startIndex = 0;
  8.     short bufferSize = 256;
  9.     long bytesLeft = bufferSize;
  10.     short bytesToRead = bufferSize;
  11.     byte[] outputBuffer = new byte[bufferSize];
  12.  
  13.     // Write bytes into the buffer
  14.     do
  15.     {
  16.         // Read the next set of bytes
  17.         bytesLeft = reader.GetBytes(reader.GetOrdinal("Attachment"), startIndex, outputBuffer, 0, bytesToRead);
  18.         // Write what we've got to the file
  19.         binaryWriter.Write(outputBuffer);
  20.         binaryWriter.Flush();
  21.         // Increment the marker position in the database field
  22.         startIndex += bytesToRead;
  23.         // Work out how many bytes to read next iteration
  24.         bytesToRead = (short)Math.Min(bytesLeft, bufferSize);
  25.  
  26.     } while (bytesLeft > 0);
  27.  
  28.     binaryWriter.Close();
  29.     fileStream.Close();
  30. }
Dec 11 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

20
5556
by: cylin | last post by:
Dear all, I open a binary file and want to write 0x00040700 to this file. how can I set write buffer? --------------------------------------------------- typedef unsigned char UCHAR; int...
1
13222
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...
1
1635
by: James Dean | last post by:
i want to decode 2 byte and 1 byte char data......because japanese characters take up 2 bytes ordinary characters 1 byte.....can u convert one byte array so that the 2 byte and 1 byte information...
2
3924
by: Alessandro | last post by:
Hi everyone... I'm a beginner in C#, I'm trying to: -> check the BatteryLifePercent, and put the value into a string; ->check the ACLineStatus to know if the device is connected to external...
5
3636
by: philip | last post by:
Here is some lines of code than I wrote. You can copy/paste theis code as code of form1 in a new project. My problem is this one : I try to write in a file a serie of bytes. BUT some bytes...
9
5020
by: pointer noob | last post by:
Hi, I am trying to write a bit of code to iterate through memory addresses and if the address is divisable by 2 then write one byte, if not write a different byte. I am having trouble with the...
0
789
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted...
3
14032
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted...
4
5643
by: | last post by:
Hi all, I want to create a method that does the following: 1) Programmatically instantiate a new XmlDataSource control 2) For each file in a named directory, make a "FileSystemItem" element 3)...
0
7252
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,...
0
7153
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...
0
7432
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...
0
7517
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5676
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,...
1
5077
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...
0
3218
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1583
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 ...
1
791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.