error cannot convert from 'object' to 'string'
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?
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
)
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.
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()
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];
精彩评论