1

I get some errors in my code below could any one help?

error cannot convert from 'object' to 'string' The best overloaded method match for 'System.IO.File.Exists(string)' has some invalid arguments

string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;");
cn.Open();

OdbcCommand sc = new OdbcCommand(string.Format("SELECT picturepath FROM Pictures WHERE UserID ='{0}'", theUserId), cn);
OdbcDataReader reader = sc.ExecuteReader();
while (reader.Read())
{
if (System.IO.File.Exists(reader[0]))
{  // error cannot convert from 'object' to 'string'
   // The best overloaded method match for 'System.IO.File.Exists(string)' has some invalid arguments
    System.IO.File.Delete(reader[0]);
}  // error cannot convert from 'object' to 'string'
   // The best overloaded method match for 'System.IO.File.Delete(string)' has some invalid arguments
}

How can this be fixed?

2
  • 3
    Careful... you've got a SQL injection vulnerability here. Commented Mar 25, 2011 at 22:32
  • 1
    yup I know :) thanks tho Commented Mar 25, 2011 at 22:38

4 Answers 4

11

Replace reader[0] with either:

reader.GetString(0)

or

Convert.ToString(reader[0])

(since reader[0] is for arbitrary data, so typed as object - but that method expects a string)

Sign up to request clarification or add additional context in comments.

Comments

1

The quick solution is this:

// note addition of "as string"
if (System.IO.File.Exists(reader[0] as string))

However you should be sure that the element at that position really is a string.

2 Comments

Actually, I'd use (string)reader[0] if going this route; the exception message will be clearer if we get it wrong - cast vs null-arg)
See that too often. as should almost always be followed by a null check, never used directly.
0

If reader[0] is indeed a string object, reader[0].ToString() will return the string value.

While debugging, you can check what type reader[0] by calling the get type method in the immediate window.

e.g. reader[0].GetType()

Comments

0
OleDbDataAdapter da = new OleDbDataAdapter("select fact_code,fact_cost,fact_date from factor where fact_date between '" + int.Parse(comboBox2.SelectedItem )+ "/" + int.Parse(comboBox1.SelectedItem) + "/" + int.Parse(comboBox3.SelectedItem) + "'and '" + int.Parse(comboBox5.SelectedItem) + "/" + int.Parse(comboBox4.SelectedItem) + "/" + int.Parse(comboBox6.SelectedItem) + "'", con);
                DataSet dt = new DataSet();
                da.Fill(dt);
                dataGridView1.DataSource = dt.Tables[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.