473,769 Members | 1,640 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Save data from DB (BLOB)

5 New Member
Hello,
I've got very odd problem.
I use windows application to store files in data base (MySql) and then to extract this files from data base and save it on hdd. But when i save them back to hdd tihs files are 1Kb less from original file. When i insert pictures this 1kb obviously is not imported and the pictures is shown. But other files when try to be opened is corrupted or if they open some error message is shown.
So the code that i use to save file in DB is:

Expand|Select|Wrap|Line Numbers
  1.           MySqlConnection con = new MySqlConnection("SERVER=localhost;" +
  2.                 "DATABASE=dbname;" +
  3.                 "UID=user;" +
  4.                 "PASSWORD=user;");
  5.  
  6.             MySqlDataAdapter da = new MySqlDataAdapter("Select * From test", con);
  7.             MySqlCommandBuilder MyCB = new MySqlCommandBuilder(da);
  8.             DataSet ds = new DataSet("test");
  9.  
  10.             da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  11.             FileStream fs = new FileStream(@"C:\image.rar", FileMode.OpenOrCreate, FileAccess.Read);
  12.  
  13.             byte[] MyData = new byte[fs.Length];
  14.             fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
  15.  
  16.             fs.Close();
  17.  
  18.             da.Fill(ds, "test");
  19.  
  20.             DataRow myRow;
  21.             myRow = ds.Tables["test"].NewRow();
  22.  
  23.             myRow["id"] = "12";
  24.             myRow["blobdata"] = MyData;
  25.             ds.Tables["test"].Rows.Add(myRow);
  26.             da.Update(ds, "test");
  27.  
  28.             con.Close();
  29.  
The code that extract files from database and save them to hdd is:

Expand|Select|Wrap|Line Numbers
  1.           MySqlConnection con = new MySqlConnection("SERVER=localhost;" +
  2.                 "DATABASE=dbname;" +
  3.                 "UID=user;" +
  4.                 "PASSWORD=user;");
  5.  
  6.             MySqlDataAdapter da = new MySqlDataAdapter("Select * From test where id = 12", con);
  7.             MySqlCommandBuilder MyCB = new MySqlCommandBuilder(da);
  8.             DataSet ds = new DataSet("test");
  9.  
  10.             byte[] MyData = new byte[0];
  11.  
  12.             da.Fill(ds, "test");
  13.             DataRow myRow;
  14.             myRow = ds.Tables["test"].Rows[0];
  15.  
  16.             MyData = (byte[])myRow["blobdata"];
  17.             int ArraySize = new int();
  18.             ArraySize = MyData.GetUpperBound(0);
  19.  
  20.             FileStream fs = new FileStream(@"C:\Data\image.rar", FileMode.OpenOrCreate, FileAccess.Write);
  21.             fs.Write(MyData, 0, ArraySize);
  22.             fs.Close();
  23.  
Can someone help me to find missing Kb :-)

Thanks!
Jul 3 '08 #1
5 7618
Plater
7,872 Recognized Expert Expert
fs.Read() returns an integer value that says how many bytes were actually read. It's possible the amount of data you want cannot be read with one Read() call, you should start by checking there?
(Or am I looking at the wrong spot for missing data?)

I would also recomend looking at the column DataType for the "blobdata" column. It might be coming in as not the expected datatype and thus some data is being truncated?(The lost data kinda sounds like a string conversion is happing somewhere)
Jul 3 '08 #2
countnazgul
5 New Member
fs.Read() returns an integer value that says how many bytes were actually read. It's possible the amount of data you want cannot be read with one Read() call, you should start by checking there?
(Or am I looking at the wrong spot for missing data?)

I would also recomend looking at the column DataType for the "blobdata" column. It might be coming in as not the expected datatype and thus some data is being truncated?(The lost data kinda sounds like a string conversion is happing somewhere)
Sorry is not 1Kb but 1b.
The column "blobdata" is from type LONGBLOB (i try and with another BLOB type but the result is the same)
Jul 3 '08 #3
Plater
7,872 Recognized Expert Expert
Ok, on closer inspection I think the problem is this:
Expand|Select|Wrap|Line Numbers
  1. int ArraySize = new int();
  2. ArraySize = MyData.GetUpperBound(0);
  3.  
What is that? It should not be needed (and would explain why you are off by one byte)

You should be using more like this:
Expand|Select|Wrap|Line Numbers
  1. fs.Write(MyData, 0, MyData.Length);
  2.  
Jul 3 '08 #4
Curtis Rutland
3,256 Recognized Expert Specialist
Ok, on closer inspection I think the problem is this:
Expand|Select|Wrap|Line Numbers
  1. int ArraySize = new int();
  2. ArraySize = MyData.GetUpperBound(0);
  3.  
What is that? It should not be needed (and would explain why you are off by one byte)

You should be using more like this:
Expand|Select|Wrap|Line Numbers
  1. fs.Write(MyData, 0, MyData.Length);
  2.  
That's the only thing that I did differently in a similar project I did recently and everything works fine for me. I also think that may be where your problem stems from.
Jul 3 '08 #5
countnazgul
5 New Member
Thanks for answers!
I find solution that is similar to this but works for me ;-)
And here is the code:
Expand|Select|Wrap|Line Numbers
  1.  
  2.             MySqlConnection Conn = new MySqlConnection("SERVER=localhost;" +
  3.             "DATABASE=db;" +
  4.             "UID=user;" +
  5.             "PASSWORD=root;");
  6.  
  7.             MySqlCommand Cmd = new MySqlCommand("Select * From test where id = 19", Conn);
  8.             Cmd.CommandType = CommandType.Text;
  9.             Conn.Open();
  10.             MySqlDataReader Reader = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
  11.             FileStream FStream = null;
  12.             BinaryWriter BWriter = null;
  13.  
  14.             byte[] Binary = null;
  15.             const int ChunkSize = 100;
  16.             int SizeToWrite = 0;
  17.             MemoryStream MStream = null;
  18.  
  19.             while (Reader.Read())
  20.             {
  21.                 FStream = new FileStream(@"c:\Data\Nomenclature123.xls", FileMode.OpenOrCreate, FileAccess.Write);
  22.                 BWriter = new BinaryWriter(FStream);
  23.                 Binary = (Reader["blobdata"]) as byte[];
  24.                 SizeToWrite = ChunkSize;
  25.                 MStream = new MemoryStream(Binary);
  26.  
  27.                 for (int i = 0; i < Binary.GetUpperBound(0) - 1; i = i + ChunkSize)
  28.                 {
  29.                     if (i + ChunkSize >= Binary.Length) SizeToWrite = Binary.Length - i;
  30.                     byte[] Chunk = new byte[SizeToWrite];
  31.                     MStream.Read(Chunk, 0, SizeToWrite);
  32.                     BWriter.Write(Chunk);
  33.                     BWriter.Flush();
  34.                 }
  35.                 BWriter.Close();
  36.                 FStream.Close();
  37.             }
  38.             FStream.Dispose();
  39.  
Thanks again!
Jul 3 '08 #6

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

Similar topics

1
3257
by: SOAP | last post by:
how to save binary data to database by using CMP2.0? I would like to save a save image to database through EJB. but I don't know which data type shoud I use. any examples? thanks a lot
4
3003
by: Luis | last post by:
Hi, I can a big problem... because I have a byte data = new byte, and I need to save this to a field on my MySQL database (here I have a BLOB field) but ¿can I save it? because if I put: Insert into archiv(ref, databinary) VALUES('"+ref+"', '"+ data+"') In my Database only save "System.byte" Can Someone help me?
4
3076
by: dale zhang | last post by:
Hi, I have a C# web application in ASP.Net, which has a user contact info DB in MS Access. Can I add a column to each user to save pdf attachments for each user if needed? If so, how do we do this? Thanks for help. -Dale
1
8714
by: Markusek Peter | last post by:
Hi, I'm using MySQLDriverCS. I've got no problem to store BLOB into database, but I can't get it back(save to file). Problem is with DataTable(returns string:( ) My code: -- DataTable dt = new MySQLSelectCommand(...; //select that row and column where is BLOB string dest = Server.MapPath("image.jpg"); FileStream binFile = new
2
2221
by: Recep TARAKÇI | last post by:
hi how i can read and write image file a sql server database. thanks
0
2413
by: Big George | last post by:
Hello, I'm trying to save a jpg file of 300KB as a BLOB field in an Oracle 10g Database. If I try to call a Stored Procedure, it fails. If I use CommandText with SQL sentence, it success. I can't save the jpg file as a BLOB field using this Method (I'm calling a Stored Procedure): Private Sub save_BLOB(ByVal Photo As Byte())
2
6534
by: Vinciz | last post by:
hi guys... im new in java and i would love to learn some of these... basically i got a sample code to retrieve the blob from the mysql. however, i dont really know what to do with these retrieved byte/binary data as i got no idea on how to save them in our pc. For this situation, what i need to do is give the byte/binary data an extension (retrieved from another field in the table) in order to revert back to the original data i had in the...
4
5491
by: kev | last post by:
Hi folks, I have created a database to store information on equipments. During the first level of registration, there is a form that i need the user to fill up details on the equipment testing. i have done this one.Now what i need is to enable the users to upload files and save it into the corresponding table. Example: 3. A laser inventory form has been completed for each 3b or 4 laser and submitted to the Laser Safety Officer...
6
4465
by: =?Utf-8?B?UHVjY2E=?= | last post by:
Hi, I'm using VS2005, .net 2 and C# for windows application. I need to convert a IntPtr to a byte to be able to add a meetingBlob data to the meeting class object in Active Directory schema. I get a "unspecified error" if I tried to add the data before converting to a byte in "deNewContextObject.Properties.Add((object)blob.pData);". public struct Blob { public IntPtr pData; public int nLength;
0
9589
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
9423
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
10211
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8870
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...
1
7408
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6673
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
5298
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...
1
3958
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
3
2815
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.