So my fileupload function had been working for awhile but all of a sudden it had stopped working and the problem remained even after I tested it in a new project and reverted to the older version of the code.
Below is the code of my upload function.
public void EnsureDirectoriesExist()
{
string currentuser = "admin";
//string currentuser = (string)(Session["uname"]);
// if the \pix directory doesn't exist - create it.
if (!System.IO.Directory.Exists(Server.MapPath(@"~/userimages/" + currentuser + "/displaypicture/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(@"~/userimages/" + currentuser + "/displaypicture/"));
}
}
protected void uploadbtn_Click(object sender, EventArgs e)
{
string currentuser = "admin";
//string currentuser = (string)(Session["uname"]);
if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".png")
{
// create posted file
// make sure we have a place for the file in the directory structure
EnsureDirectoriesExist();
String filePath = Server.MapPath(@"~/userimages/" + currentuser + "/displaypicture/" + FileUpload1.FileName);
String filePath2 = ("~/userimages/" + currentuser + "/displaypicture/" + FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
string mySQL, mySQL2;
mySQL2 = "DELETE FROM displaypicture WHERE username='" + currentuser + "'";
mySQL = "INSERT INTO displaypicture(username,path) VALUES ('" + currentuser + "','" + filePath2 + "')";
conn.Open();
SqlCommand cmdAdd2 = new SqlCommand(mySQL2, conn);
SqlCommand cmdAdd = new SqlCommand(mySQL, conn);
cmdAdd2.ExecuteNonQuery();
cmdAdd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Upload successful!");
}
else
{
MessageBox.Show("Upload has failed. Please check file format.");
}
}
So basically I get brought to the else function as the if function doesn't seem to be correct. However I could have sworn that it worked for about 2 weeks before suddenly not working. I have also switch the if function to,
if(currentuser.equals("admin")){
}
to test if my if else requirement statement was correct and when I did that, the if function gets run however only the directories are created but the file isn't uploaded into the directory.