开发者

Exporting mysql blob to xml then importing back dont get the same result in c#

开发者 https://www.devze.com 2023-02-09 03:39 出处:网络
I have some photos (not big, only 8kb) in mysql database (in my desktop). the field type is blob. actually i want to export the table to xml file then upload it to my database website. 开发者_运维问答

I have some photos (not big, only 8kb) in mysql database (in my desktop). the field type is blob. actually i want to export the table to xml file then upload it to my database website. 开发者_运维问答but it failed. I try to mimic it by exporting the table to xml file then importing it back to another table (the table's structure is same). I can do it but i don't get the same photos (only some encoding text). Here is some pieces of code:

Exporting the table to xml :

FileStream fs = new FileStream(filename,FileMode.Create,FileAccess.Write,FileShare.None);
StreamWriter sw = new StreamWriter(fs,Encoding.ASCII);
ds.WriteXml(sw);  //write the xml from the dataset ds

Importing the xml to the dataset :

FileStream fs = new FileStream(filename,FileMode.Open);
DataSet ds = new DataSet();
ds.ReadXml(fs);

Writing the dataset to another table :

   ...
   int count = ds.Tables[0].Rows.Count;
   for(int i=0;i<count;i++)
   {  
       DataRow myDR = ds.Tables[0].Rows[i];
       ...
       byte[] myphoto = null;
       if(myDR["myphoto"].ToString().Length > 0)
       {
          myphoto = Encoding.ASCII.GetBytes(myDR["myphoto"].ToString().ToCharArray());
       }
       //insert the data to the mysql table 
       ...
   }
   ...

Why i don't get the same photos in this another table?

sorry for my bad english.


Looking at this:

myphoto = Encoding.ASCII.GetBytes(myDR["myphoto"].ToString().ToCharArray());

you are treating arbitrary binary data as encoded text; that cannot work. An Encoding is intended to turn text data into binary (of a given text format, i.e. the encoding), and to turn binary (of a given text format) back into text; it cannot treat arbitrary binary (that isn't in the expected format) as text. As a trivial example, ASCII only uses 7 bits of each octet; any octet with the MSB set is guaranteed to get corrupted at some point during this cycle.

If you want to represent binary data as a string, use base-64:

string s = Convert.ToBase64String(blob);

to convert back:

byte[] blob = Convert.FromBase64String(s);
0

精彩评论

暂无评论...
验证码 换一张
取 消