Link to home
Start Free TrialLog in
Avatar of Enid_JP
Enid_JP

asked on

c# : Insert .rpt file into database.

Hi,
I need to add a crystal report file to a database;
it could be Sql Server/Oracle.
I have the following code;
What am I doing wrong?
I am just trying this for the SQL server 2005 database;
-------------
string sFilePath = "C\\test.rpt";
//byte[] RptData = GetRPTData(sFullReportPath);
FileStream fs = new FileStream(sFilePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] FileData = br.ReadBytes((int)fs.Length);
SqlCommand cmd = new SqlCommand("INSERT into Tab1 (Creator,Contents ) values(?,?)",myConnection);
cmd.Parameters.AddWithValue("Creator", "Tom");                
 SqlParameter blob = new SqlParameter();
   // blob.DbType = DbType.Byte;
 blob.SqlDbType = SqlDbType.VarBinary;
 cmd.Parameters.Add(RptData);
 int i =  cmd.ExecuteNonQuery();
I get an error for cmd.Parameters.Add(RptData);
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll

Additional information: The SqlParameterCollection only accepts non-null SqlParameter type objects, not Byte[] objects.
Avatar of hongjun
hongjun
Flag of Singapore image

Your file path is incorrect. You are missing the colon.
Use this instead.
string sFilePath = @"C:\test.rpt";

Open in new window

Avatar of Enid_JP
Enid_JP

ASKER

That was a typo when I edited the contents.
The real problem is that '?' is not accepted; the paremeter names have to be given in INSERT statement.
I got it working with the following code:
SqlCommand cmd = new SqlCommand("INSERT into Tab1 (CREATOR,CONTENTS) values(@CREATOR,@CONTENTS)", myConnection);
SqlParameter Creator = new SqlParameter("@CREATOR", SqlDbType.Char);
            Creator .Value = "USER1";
            cmd.Parameters.Add(Creator);
FileStream fs = new FileStream(sFullFilePath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            byte[] FileData = br.ReadBytes((int)fs.Length);
 
SqlParameter Contents = new SqlParameter("@CONTENTS", SqlDbType.Image);
            Contents .Value = FileData ;
            cmd.Parameters.Add(Contents );
       int i =  cmd.ExecuteNonQuery();
       --------------
This works only on SQL Server; when I use ODBCCommand this does not work; I think I will have to use '?' instead of parameter names in the INSERT T statement.
ASKER CERTIFIED SOLUTION
Avatar of hongjun
hongjun
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial