Reputation: 313
I have an application that I am using as a file uploader with an admin panel on the backend of things. I have most of everything completed on it, but I'm running into a wall where I can't delete the physical file from the server. Permissions are correct to allow such action.
On the click of a delete button next to the entry I'm calling the primary ID of the row and as such I'm able to call from the SQL the stored filePath. Here's my code to do so:
DbConn dbConnx = new DbConn();
SQL = "SELECT filePath FROM database WHERE id='"+ primaryID +"'";
myReader = dbConnx.createDataReader(SQL);
string fn44 = Convert.ToString(myReader.Read());
string url = fn44; //I know redundant
System.IO.File.Delete(url);
All I'm able to gather is that the only information that is pulled is 'true'. I believe this is because I'm trying to convert the information to a string and it doesn't like that. How would I go about taking the value stored in SQL and using it with a variable to perform the delete?
Any help/resources would be greatly appreciated.
Upvotes: 3
Views: 1303
Reputation: 216358
I don't know the datatype of myReader, but assuming that is a DataReader of some kind then calling
myReader.Read();
returns a boolean value that tells you if the datareader is positioned on a valid row or not.
To get the content of the record on which the reader is positioned (assuming the previous call returns true) you need to write
myReader = dbConnx.createDataReader(SQL);
if(myReader.Read())
{
string fn44 = Convert.ToString(myReader[0]);
....
}
Your code has another problem called Sql Injection.
You should not use string concatenation with user input when building a sql command.
You use a parameterized query like this
SQL = "SELECT filePath FROM database WHERE id=@p1";
using(SqlConnection con = new SqlConnection(......))
using(SqlCommand cmd = new SqlCommand(SQL, con))
{
con.Open();
cmd.Parameters.AddWithValue("@p1",primaryID);
using(SqlDataReader myReader = cmd.ExecuteReader())
{
.....
}
}
yyy
Having fixed the reading from the database, now you need to check what kind of string is stored in the FilePath field in the database. Remember that every file IO operation on a web site should get to the effective file name using the Server.MapPath method
Upvotes: 5