2

I'm using this code to copy data from a 2d object array into the memory stream. The memory stream shows the count of the data that has been read from the 2d array. But in the end I'm getting an empty string. I can't understand why. However, using the soapformatter, the string is not empty but it's enclosed in soap format so that isn't useful. Here's the code with BinaryFormatter.

        Worksheet sheet = (Worksheet)workBookIn.Sheets[1];
        Range excelRange = sheet.UsedRange;
        object[,] valueArray = (object[,])excelRange.get_Value(
            XlRangeValueDataType.xlRangeValueDefault);
        using (var ms = new MemoryStream())
        {
            BinaryFormatter formatter = new BinaryFormatter();
            //valueArray = 2d object array
            formatter.Serialize(ms, valueArray);
            ms.Position = 0;
            return Encoding.UTF8.GetString(ms.ToArray());
        }
  • You can't serialise an array and then expect it return a string. More than just the actual contents of the array are stored by the formatter. I suspect what you actually want is to just put the values of the array into a string, so then you should not use a binary formatter. – MicroVirus May 10 '16 at 09:33
  • Thank-you. What should I use then? How to get the values from the 2d object array into a string? Kindly help out. – automationFormation May 10 '16 at 09:43
  • That depends, we need to know the definition of `valueArray`, so could you edit it into your question? – MicroVirus May 10 '16 at 09:44
  • Never, Never convert binary data to a string it doesn't work. Strings are two byte objects with a private property that indicates if each character is one or two bytes. Strings will corrupt the binary data. When sending/receiving binary data you must either send fixed length data and/or send a byte count at the beginning of message indicating how many bytes are being sent. If you are sending a real/.imaginary array you can send a 32 bit real and 32 bit imaginary so each value is 8 bytes and then send a byte count of the number of the number of values being sent. – jdweng May 10 '16 at 10:01

1 Answers1

0

I think you must be using XmlSerializer as follows:

    Worksheet sheet = (Worksheet)workBookIn.Sheets[1];
    Range excelRange = sheet.UsedRange;
    object[,] valueArray = (object[,])excelRange.get_Value(
        XlRangeValueDataType.xlRangeValueDefault);

    XmlSerializer xs = new XmlSerializer(valueArray.GetType());

    using(StringWriter sw = new StringWriter())
    using(XmlWriter writer = XmlWriter.Create(sw))
    {
         xs.Serialize(writer, valueArray);
         var xml = sw.ToString(); // Your XML
    }
Deepak Bhatia
  • 1,090
  • 1
  • 8
  • 13