Question

We have an ancient foxpro application with a function which has to be converted to C#.

Basically, all it does is to read a XLS file from a SQL Server database table and save it on the local disc. This file serves as an Excel worksheet template.

The binary XLS file information is stored in a TEXT column (which makes me nervous) and is extracted via FoxPro with this single line:

lnResult = SQLEXEC(THISFORM.Hconn, "select XExcell from MyTable", "xy")
SELECT xy
IF !EMPTY(xy.xExcell) AND !ISNULL(xy.xExcell)
  COPY  memo xy.xExcell to (SomeFile)

The problem is that C# (or at least the ADO command) treat the column as a string. Well, that is what the reader comes up with when I execute a

MyADOCommand.ExecuteScalar();

Edit: Which is an implicit string and cannot be casted to a byte array.

So, here's my problem: The data is in some binary form in the SQL Server and has to be pulled and treated as a raw byte array (and finally written to disc, giving it an extension of .XLS and pray that Excel is able to read the file).

Any idea how to achieve this? The following code obviously does not work

var s=(string)cmd.ExecuteScalar();
var enc = new System.Text.ASCIIEncoding(); 
var template= enc.GetBytes(s);
var fs = new FileStream(excelTemplateFile, FileMode.OpenOrCreate, FileAccess.Write);
var bw = new BinaryWriter(fs);
bw.Write(template);
bw.Flush();
bw.Close();
fs.Close();

I also tried to cast the TEXT column as an IMAGE, but that does not work either (SQL Server complains that it cannot convert). I know the problem is the fact that a text (a string of characters) is not a stream of bytes, but if FoxPro can do it, C# should be able as well, no?

Edit: The contents is approx 3MB big.

Was it helpful?

Solution

Change the SQL query to cast the column to varbinary as follows:

select cast(cast(XExcell as varchar(max)) as varbinary(max)) from MyTable

Then:

var bytes = (byte[])cmd.ExecuteScalar();

using (var writer = new BinaryWriter(File.Open("your file name", FileMode.Create))) 
{
   writer.Write(bytes);
}

EDIT: Double casting TEXT -> varchar(max) -> varbinary(max), because direct casting from TEXT -> varbinary(max) is not allowed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top