Unable to cast object of type 'System.String' to type 'System.Byte[]' error

Hello,

I have some binary data in a MySQL database, and im trying to convert it to a file.

Before, when i was using the ms sql express 2005 database, everything was working fine. But then i migrated to MySQL because of budget issues. The following is the block of code that produces the error.

private void showDbImage()

{

string ImageId = Request.QueryString["img"];

 

//build our query statement

string sqlText = "SELECT DownloadFile, DownloadType FROM DownloadTable WHERE DownloadName = '" + ImageId +"'";

 

OdbcConnection connection = new OdbcConnection( ConfigurationManager.ConnectionStrings["mySqlConnectionString"].ConnectionString );

OdbcCommand command = new OdbcCommand( sqlText, connection );

//open the database and get a datareader

connection.Open();

OdbcDataReader dr = command.ExecuteReader();

if (dr.Read()) //yup we found our file

{

Response.ContentType = dr[
"DownloadType"].ToString();Response.BinaryWrite((byte[])dr["DownloadFile"]); //downloadFile is the column that contains the binary data

}

connection.Close();

}

However, when this code runs, i get the following error in my browser.

Unable to cast object of type 'System.String' to type 'System.Byte[]'.

The "DownloadFile" column contains the binary data of the file, and its a "LONGTEXT" type.

Before, when i was using sql express 2005, the column was defined as an "image" type. But since the image type does not exist in MySQL,i used "LONGTEXT" instead. Could this be the problem?

 

Any help will be greately appreciated.

Thank you.

0
hervens
6/30/2007 12:53:38 AM
asp.net.getting-started 91979 articles. 3 followers. Follow

2 Replies
3307 Views

Similar Articles

[PageSpeed] 16

OK - you confused me - you said:
"But then i migrated to MySQL because of budget issues"

SQL Server express is free - MySQL is free - what causes a budget issue?


David Wier
MCP/ASPInsider
ASPNet101.com - where to look first!
Please Vote for ASPNet101 - 'Best Community Resource'!
Control Grouper - easily control properties for multiple controls with one control!
Calendar Express - The Best HTML Calendar Generator on the web!
(Please 'Mark as Answer' when it applies)
0
augustwind
6/30/2007 1:16:23 AM

Sorry for long reply. I was having internet connection problems

What i really meant is that, i migrated to MySQL because it fits my needs better. Because in almost every web hosting company i go to, they would usually say something like:

Total Disk space: 50gb

Total MySQL database space: unlimitted ( shared with disk space)

Total Ms sql server 2005 space: 50mb

Or some other times, they dont support Ms sql server 2005 at all.

And database space and compability issues is highly important to me, as i am developping a file sharing website, and EVERY uploaded file is transformed into binary, and stored in my database. And that includes large videos, and .zip files. ( 500mb+ ). Not to mention that i read somewhere, that you cannot store more than 3gb of data in a ms sql express database.

And as for the initial question, in initial post, i found the answer. I received the error because i was trying to store files, as a "longtext" type into the MySQL database.

The equivalent of the "IMAGE" type in ms sql express 2005 is "BLOB" in MySQL.

I hope this helps anyone who was being faced with the same problem

Thank You.

0
hervens
7/5/2007 1:59:30 AM
Reply:

Similar Artilces:

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte[]'.
Hi All, I am trying to retrieve a Picture from an SQL 2005 database. Here is my code:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim ListingID As String = (Request.QueryString("GUID")) 'Connect to the database and bring back the image contents & MIME type for the specified pictureUsing myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionStringListings").ConnectionString) Const SQL As String = "SELECT [Pic1Ext], [Picture1] FROM [Listings] WHERE [ListingID] = @ListingID"C...

How do I get around this error "Unable to cast object of type 'System.DBNull' to type 'System.String' "
I am using Visual Developer 2008 Express Edition for the first time, and I keep getting the following error below. The site allows anyone to enter with a valid username and password, but even when I logoff the site I get the same error....like the memory or database is not getting refreshed. I would think that when I initially compile the site that anything left in memory would be flushed out. Can someone please help me to figure this out. Thanks,Ramell P.S. The site is programmed using C#    Unable to cast object of type 'System.DBNull' to type 'System.String&...

ERROR: Unable to cast object of type 'System.Boolean' to type 'System.String'
I created a class to update, insert, select and delete data with an object data source but I am getting the following error... body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-wei...

System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'
Hello , I am a data table with null able Columns.I am not able to catch the value for DBNull. I did set a value to be returned as empty in dataset. Here is the code where i am trying to catch.1 public List GetStores() 2 { 3 List tmpStore = new List(); 4 StoresService.shopDBDataSet.StoresDataTable stores = 5 storesService.GetStores(); 6 for (int i = 0; i < stores.Count ; i++) 7 { 8 Store store = new Store(); 9 store.StoreID = stores[i].StoreID...

SqlDataSource.Select Error: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.
I am trying to use the select statement to put a field from my database using a SqlDataSource named 'FileBase.' I am using the following code: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'" myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String)But when I run the code I get the following error:Server Error in '/YorZap' Application. Unable to cast object of type 'System.Data.DataView' to type 'System.String'. Description:...

SqlDataSource.Select Error: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.
I am trying to put the data from a field in my database into a row in a table using the SQLDataSource.Select statement. I am using the following code: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'" myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String)But when I run the code, I get the following error:Server Error in '/YorZap' Application. Unable to cast object of type 'System.Data.DataView' to type 'System.String'. Descri...

"Unable to cast object of type 'System.String' to type 'System.String[]'."
hi i'm using the following statement in my applicationstring[] strTArray = new string[5]; strTArray = (string[])(Session["TextDataArray"]); when i run the application its giving the below error {"Unable to cast object of type 'System.String' to type 'System.String[]'."} can anyone say how to solve this thanks in advance Archu What are you storing in the TextDataArray session? What is the data type you are storing?   RegardsBilal Hadiar, MCP, MCTS, MCPD, MCTMicrosoft MVP - Telerik MVP...

Unable to cast object of type '<>f__AnonymousType1`3[System.Guid,System.String,System.String]' to type 'aspnet_User'.???
Hi everyone, What does this error mean?  ERROR: Unable to cast object of type '<>f__AnonymousType1`3[System.Guid,System.String,System.String]' to type 'aspnet_User'. Thank's a lot /PepePepe JoseNewbie@C#.Net&jRuby What type is in your DataItem?  A Guid? or a String?  Either way, it's telling you cant cast it to a aspnet_User type.  Let us know what your DataItem is and we can help further.Good Luck and happy programming!Let's build community! If my post helped you, mark it as the Answer and I will do the same when you help me.....

Unable to cast object of type 'System.String' to type 'System.Array'
I really need to get this working! I have dimensioned fnames in line 2 to 200 slots. This code gets all the file names in a subdirectory and places them into an array. First files(), a dynamic array, gets the full path. Then line 9 splits it up into it's parts. I grab the last part (the filename) and store it into fnames. The message is  Unable to cast object of type 'System.String' to type 'System.Array'.  How do I get this to work?  Filenames is an array. Line 9 works. It takes a string (str) and converts it into the Array filenames. Why doesn't the n...

Unable to cast object of type 'System.String[]' to type 'System.IConvertible'.
hi expert   i try get the string from request.querystring("CID") from the error messege i know that is string[] (array) how to convert it to int32 and request.querystring("CID") is int value   Line 19: protected void ObjectDataSourceCarPicture_Inserting(object sender, ObjectDataSourceMethodEventArgs e) Line 20: { Line 21: e.InputParameters.Add("CID", Convert.ToInt32(Request.QueryString.GetValues("CID")) ); Line 22: // e.InputParameters.Add("CID", Convert.ToInt32( Convert.ToString( a Request.QueryString.GetValues("CID"))))); Line 23: } i already try search from google but still not get the solution Why dont you carry it out this way: string result = Request.QueryString["CID"]; //Parses the given string, throwing some kind of error when its //not a number int cid = Int32.Parse(result);And then use the cid whereever you want!Hope that helps.So simple... yet so effective.My "Life"ly Blog thanks for reply it works other that i did a mistake Request.QueryString.GetValues("CID")   to Request.QueryString.Get("CID") Watch out for the other thing that I mentioned in my code.. you can use Request.QueryString["CID"] to index into the QueryString collection. Saves some hassle.Smiles.So simple... yet so effective.My "Life"ly Blog...

Unable to cast object of type 'System.UInt32' to type 'System.String'?
Hi all,I'm trying to retrieve a column in my table (MySQL), this is the primary key of that table, and here is my code: public string GetAsocPKByUserName(string UserName) { MySqlConnection conn = new MySqlConnection(); MySqlCommand myCommand = new MySqlCommand(); string ASOC_PK = string.Empty; try { conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); myCommand = new MySqlCommand("SELECT Distinct ASOC_PK FROM asso...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi i have the following which is meant to check if an image is available and if it isnt it should show a default image however, it gives me this error whenever the image is null in the database. This is the function which returns the error;protected string FormatImageUrl(object url) {if ((url != DBNull.Value) && (url != null) && (url.ToString().Trim().Length > 0)) { //if (File.Exists(url))return (url.ToString().Trim()); } else {return "~/images/default.gif"; } } Hey,Doesn't seem to pass the dbnull check.  Try to do:  if ((!DBNull.Valu...

Unable to cast object of type 'System.DateTime' to type 'System.String'.
 Hi,      I got this field (dateSubmitted) having a data type of DateTime but I receive this error "Unable to cast object of type 'System.DateTime' to type 'System.String'."       All value for dateSubmitted field are 12/27/2007 12:00:00 AM. cheers,imperialx  imperialx:I got this field (dateSubmitted) having a data type of DateTime but I receive this error "Unable to cast object of type 'System.DateTime' to type 'System.String'." Can you explain it further as to, ...

Unable to cast object of type 'System.Int64' to type 'System.String'
Hi friends I am getting the following error..."Unable to cast object of type 'System.Int64' to type 'System.String'." for the following line of code  if ((QSDealID) == (dr.GetString(1).ToString()))...............need ur help...Gurjeet,England First of all, the ToString of the GetString method is not needed because the GetString will return a string. The prolem with your code is that QSDealID is of type System.Int64, right? So a Int64 can't be compared with a string. The DataReader have a method that can return a Int64, so instead of using GetString(1), ...

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
I'm getting Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. anyone knows how to write some code to check if my binary data is null then continue check another data? I've tried but seems that byte and string can't convert...  (hope someone can provide me code in VB and where to insert them :))  Here's my code:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim ID As Integer = Convert.ToInt32(Request.QueryString("ID"))Using myConnection As New SqlConnection(Configuratio...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi there, If I add a new event and leave the description field empty the StarterKit seems to throw a big wobbly over the null values in my DB (SQL2000). Have I made a mistake in the installation or something? The problem lies in this line: SharedRoutines.truncate((string)Eval("description")) because description is Null. I want to sort this in this line and I don't want to reply on validators? This is a known issue reported in the Identified Bugs and Fixes for the ClubSite Starter Kit post. I don't think there is one definitive answer. Search on your error message and you'll fin...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi i get the following error, Unable to cast object of type 'System.DBNull' to type 'System.String'.  A generic image is meant to appear when no image is found in the database for a particular product, this is how the code is laid out;protected string FormatImageUrl(string url) {if (url != null && url.Length > 0) { //if (File.Exists(url))return (url); } else {return "~/Images/CompanyProducts/No_image.jpg"; } }   And the html is like this; <asp:Image ID="Image1" ImageUrl='<%# (string) FormatImageUrl( (string) Ev...

Unable to cast object of type 'System.DBNull' to type 'System.String'
I have received the following error when I am logged in as administrator.  I wanted to test the load event feature.  Allows me to load and save new event.  I can view event on location view page but when I try to link to "list or calender" view I receive this error "Unable to cast object of type 'System.DBNull' to type 'System.String'.  Debug highlights the <asp:HyperlinkID as errored line. Any assistance would be greatly appreciated Brian   <DayEventTemplate> <div style="padding: 3px;"> <asp:Hyper...

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
Hi, I have developed a custom server control for .NET Framework 2.0. The server control has a property named BinaryData of type byte[]. I marked this property to be data bindable. Now, I have varbinary(Max) type of field in my SQL Database and I have used SQLDataSource and bound this varbinary(Max) field with the property BinaryData (byte[]) of my control. It is working fine as long as the data value is not NULL. Now, In my control, I have handled the NULL value so that no Exception is thrown. Still, when I bind this property using the SQLDataSource, I get Error "Unable to cast object ...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi All, I am using Sql server 2005 and VS 2005 C#. Can anybody explain howz solve this prob? Unable to cast object of type 'System.DBNull' to type 'System.String'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.Source Error: Line 3496: get { Line 3497: try { Line 3498: ...

Update error , "Unable to cast object of type 'System.DBNull' to type 'System.String'" , using DataSet as a datasource
Hi All, The following sample code is for testing dw.UpdateData using dataset as the data source. The data retrieval and display part under Form1_Load works fine. However, inputting some values in a new row and calling dw.UpdateData causes the following error: "Unable to cast object of type 'System.DBNull' to type 'System.String'" The error seems to occur when a datawindow column value has been changed from null value. Does anyone know how to fix the error ? Thank you for your advice. I use DW2.5 (build 8542), VS2005 pro, MS SQL Express. ...

SqlTableProfileProvider
Hi everyone,I'm using the SqlTableProfileProvider  to store my profile info, including a field "DOB" (date of birth) which is a DateTime type.I have no problem storing the DOB datetime field. But when I try to retrieve it using:ProfileCommon p = Profile.GetProfile(User.Identity.Name); DOB.Text = p.DOB;I get an error on the following method in the autogenerated codefile "App_Code.7y-deadj.3.cs":public virtual string DOB {        get {            return ((string)(this.GetPropertyValue("DOB"))); //ERR...

Unable to cast object of type 'System.DBNull' to type 'System.String'. #2
 Hi:I am totally new to asp.net and downloaded the club website project. I have not done anything to the events page yet but as soon as i tried to add an event I got the following error. "Unable to cast object of type 'System.DBNull' to type 'System.String'." Can someone help me out here?ThanksBrian  This bug has been covered in the Identified Bugs and fixes section.  http://forums.asp.net/t/970081.aspx There are a few solutions and discussions on fixes, you will need to read through it to find the fix. Support@aspsksolutions.com Without kno...

Unable to cast object of type 'System.DBNull' to type 'System.String'. #2
I am getting this error when I try to run the code below. The error is happening on the last for each loop || foreach (string s in dr.ItemArray) || Please see below:        private void button1_Click(object sender, EventArgs e)        {            string myOutput = "";            DataTable dt = new DataTable();            using (TextReader tr = File.O...

Web resources about - Unable to cast object of type 'System.String' to type 'System.Byte[]' error - asp.net.getting-started

Resources last updated: 2/20/2016 12:04:59 PM