简体   繁体   中英

How to insert List<> values into SQL Binary field using C#

I'm not entirely new to programming but I still see myself as a novice. I'm currently creating an Invoicing system with a max of 5 line items, this being said, I'm creating a String<> item, serializing it to store and then de-serializing it to display. So far I've managed the serializing, and de-serializing, and from the de-serialized value I've managed to display the relevant information in the correct fields.

My question comes to: HOW do I add the list of items in the String<> object to either a Binary or XML field in my SQL table? I know it should be similar to adding an Image object to binary but there's a catch there. usually:

byte[] convertToByte(string sourcePath)
    { 
        //get the byte file size of image
        FileInfo fInfo = new FileInfo(sourcePath);
        long byteSize = fInfo.Length;

        //read the file using file stream
        FileStream fStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);

        //read again as byte using binary reader
        BinaryReader binRead = new BinaryReader(fStream);

        //convert image to byte (already)
        byte[] data = binRead.ReadBytes((int)byteSize);

        return data;
    }

this kind of thing is done for an image however the whole "long" thing does not apply to the List<> object.

Any assistance would be helpful

If you simply want to store your data as "readable" text, you can use the varchar(MAX) or nvarchar(MAX) (depending on whether you need extended character support). That translates directly into a string in ADO.NET or EntityFramework.

If all you need are bytes from a string, the Encoding class will do that:

System.Text.Encoding.Default.GetBytes(yourstring);

See: http://msdn.microsoft.com/en-us/library/ds4kkd55%28v=vs.110%29.aspx

A way of saving a binary file in a string is to convert the image to a Base64 string. This can be done with the Convert.ToBase64String (Byte[]) method:

Convert.ToBase64String msdn

string convertImageToBase64(string sourcePath)
{ 
    //get the byte file size of image
    FileInfo fInfo = new FileInfo(sourcePath);
    long byteSize = fInfo.Length;

    //read the file using file stream
    FileStream fStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);

    //read again as byte using binary reader
    BinaryReader binRead = new BinaryReader(fStream);

    //convert image to byte (already)
    byte[] data = binRead.ReadBytes((int)byteSize);

    return Convert.ToBase64String (data);
}

Now you will be able to save the Base64 string in a string field in your database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM