如何从应用程序文件夹中删除图像并从数据库中删除文件名(图像名称)? [英] How to delete image from application folder and delete file name(image name) from database?

查看:119
本文介绍了如何从应用程序文件夹中删除图像并从数据库中删除文件名(图像名称)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace CrudOperationOutside
{
    public partial class StudentRegistration : System.Web.UI.Page
    {
        static string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        SqlConnection con = new SqlConnection(CS);
        SqlCommand cmd;
        SqlDataAdapter da;
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindQualification();
                BindGender();
                bindHobbies();
                bindGrid();
                Clear();

            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string HOB = "";

            for (int i = 0; i < cblHobbies.Items.Count; i++)
            {
                if (cblHobbies.Items[i].Selected == true)
                {
                    HOB += cblHobbies.Items[i].Text + ",";
                }
            }
            HOB = HOB.TrimEnd(',');

            // Get file name from file upload control.
            string FN = Path.GetFileName(fuStudentImage.PostedFile.FileName);

            if (btnSave.Text == "Save")
            {
                // Save images to Application images folder
                fuStudentImage.SaveAs(Server.MapPath("StudentImages" + "\\" + FN));

                SqlCommand cmd = new SqlCommand("sp_Student_Insert", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@SName", txtName.Text);
                cmd.Parameters.AddWithValue("@SAge", txtAge.Text);
                cmd.Parameters.AddWithValue("@GID", rblGender.SelectedValue);
                cmd.Parameters.AddWithValue("@QID", ddlQualification.SelectedValue);
                cmd.Parameters.AddWithValue("@Hobbies", HOB);
                cmd.Parameters.AddWithValue("@SFileName", FN);
                con.Open();
                int Total = cmd.ExecuteNonQuery();
                if (Total > 0)
                {
                    lblMessage.Text = "Record is saved successfully";
                }
                con.Close();
                bindGrid();
                Clear();
            }
            else
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("sp_Student_Update", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@SID",ViewState["SID"]);
                cmd.Parameters.AddWithValue("@SName", txtName.Text);
                cmd.Parameters.AddWithValue("@SAge", txtAge.Text);
                cmd.Parameters.AddWithValue("@GID", rblGender.SelectedValue);
                cmd.Parameters.AddWithValue("@QID", ddlQualification.SelectedValue);
                cmd.Parameters.AddWithValue("@Hobbies", HOB);
                if (FN != "")
                {
                    cmd.Parameters.AddWithValue("@SFileName", FN);
                    File.Delete(Server.MapPath("StudentImages" + "\\" + ViewState["FileName"]));
                    fuStudentImage.SaveAs(Server.MapPath("StudentImages" + "\\" + FN));
                    
                }
                else
                {
                    cmd.Parameters.AddWithValue("@SFileName", ViewState["FileName"]);
                }
                cmd.ExecuteNonQuery();
                con.Close();
            }
            bindGrid();
                                 
        }

        void bindGrid()
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd = new SqlCommand("select student.SID, student.SName, student.SAge, Gender.GName,Qualification.QName, student.Hobbies, student.SFileName from student join Gender on student.GID = Gender.GId join Qualification on student.QID = Qualification.QId", con);
            da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                grdStudentDetails.DataSource = ds;
                grdStudentDetails.DataBind();
            }
            con.Close();
        }

        void BindGender()
        {
            con.Open();
            cmd = new SqlCommand("select * from Gender", con); ;
            da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                rblGender.DataSource = ds;
                rblGender.DataValueField = "GID";
                rblGender.DataTextField = "GName";
                rblGender.DataBind();
            }
            con.Close();
        }
        void bindQualification()
        {
            con.Open();
            cmd = new SqlCommand("select * from Qualification", con); ;
            da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ddlQualification.DataSource = ds;
                ddlQualification.DataValueField = "QId";
                ddlQualification.DataTextField = "QName";
                ddlQualification.DataBind();
            }
            con.Close();
        }
        void Clear()
        {
            txtName.Text = "";
            txtAge.Text = "";
            btnSave.Text = "Save";
        }

        protected void grdStudentDetails_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EDT")
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_Student_Edit", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@SID", e.CommandArgument);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    txtName.Text = ds.Tables[0].Rows[0]["SName"].ToString();
                    txtAge.Text = ds.Tables[0].Rows[0]["SAge"].ToString();
                    rblGender.SelectedValue = ds.Tables[0].Rows[0]["GID"].ToString();
                    ddlQualification.SelectedValue = ds.Tables[0].Rows[0]["QID"].ToString();
                    string[] arr = ds.Tables[0].Rows[0]["Hobbies"].ToString().Split(',');
                    cblHobbies.ClearSelection();

                    for (int i = 0; i < cblHobbies.Items.Count; i++)
                    {
                        for (int j = 0; j < arr.Length; j++)
                        {
                            if (cblHobbies.Items[i].Text == arr[j])
                            {
                                cblHobbies.Items[i].Selected = true;
                                break;
                            }
                        }
                    }
                    ViewState["FileName"] = ds.Tables[0].Rows[0]["SFileName"].ToString();
                    ViewState["SID"] = e.CommandArgument.ToString();
                    btnSave.Text = "Update";

                }
                con.Close();
            }
            else if (e.CommandName == "DLT")
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_Registration_Delete", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@RID", e.CommandArgument);
                cmd.ExecuteNonQuery();
                con.Close();
                
            }
        }
    }
}

  
                        
                    
   
                        
                    
                    <asp:TemplateField HeaderText="Action">





我的尝试:



当我从图像文件夹中删除图像时,它不会从数据库中删除文件名吗?



谢谢。



What I have tried:

When i delete image from image folder then it does not delete file name from database?

Thanks.

推荐答案

中添加此代码块删除命令事件

Add this code block in Delete Command Event
string id = e.CommandArgument;
// get the file name from the database
string filename = YourFunctionToGetFileNameFromTable(id);
 File.Delete(Server.MapPath("Files") + "\\"  +  filename));


您的代码并不完全清楚。你发布了你的按钮点击代码,但看起来你决定它是否是保存按钮,如果没有它是更新按钮。



Your code isn't exactly clear. You posted your button click code but it looks like you are deciding if it is the save button and if not it is the update button.

if (Btnsave.Text == "Save")
           {





然后你有一个行命令,我不知道知道那是什么,但这看起来像你的删除逻辑在哪里我看到EDT的检查(假设基于存储的proc名称编辑)否则它是删除命令





Then you've got a row command, which i don't know what that is, but this looks like where your delete logic is as i see a check for EDT (assuming Edit based on stored proc name) otherwise it is the delete command

if (e.CommandName == "EDT")
            {





所以说,我会用两种可能性回答这个问题。



1)在你的行命令代码中,你有一个usp_Registration_Delete的调用。在此IF语句中,您应该执行删除操作。由于我无法访问您的计算机/代码,因此我必须做出许多假设。但是在你的EDT if block中,你有这条线





So with that said, i'll answer this questions with two possibilities.

1) Inside your row command code you've got a call to usp_Registration_Delete. Inside this IF statement is where you should perform your delete operation. Since i don't have access to your computer/code I'm having to make many assumptions. But in your EDT if block, you've got this line

ViewState["Files"] = ds.Tables[0].Rows[0]["Files"].ToString();





如果这是您要删除的文件名。在DLT if块内部是你要删除文件的地方。





If that is the filename you wish to delete. The inside the DLT if block is where you would delete the file.

else if (e.CommandName == "DLT")
            {
var fileToDelete = ds.Tables[0].Rows[0]["Files"].ToString();
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_Registration_Delete",con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@RID",e.CommandArgument);
                cmd.ExecuteNonQuery();
                con.Close();

                // Delete The File Here
                File.Delete(fileToDelete);

                Fill_Grid();
            }





2)如果你发布的第一个代码块是唯一的按钮点击,那么你需要添加另一个如果声明确定是否删除vs保存vs删除



基本上





2) If the first block of code you posted is the sole button click, then you need to add another if statement to determine if it is delete vs save vs delete

Basically

if (Btnsave.Text == "Save")
{
}
else if (Btnsave.Text == "Update")
{

}
else if (Btnsave.Text == "Delete")
{

}





如果这是需要发生的事情,那么你只需要从上面发布的选项1)中获取代码,将其置于Btnsave.Text ==删除中,如果阻止,然后删除t他使用您在上面发布的FN变量进行归档(假设该文件要删除)。





If this is what needs to happen, then you just take the code from option 1) i posted above, place it inside the Btnsave.Text == "Delete" if block, and then delete the file using the FN variable you posted above (assuming thats the file to delete).

FN = Path.GetFileName(fufile.PostedFile.FileName);
File.Delete(FN);





如果没有一个能引导你朝着正确的方向前进,我会鼓励你在您的初始帖子上使用改善问题链接添加更多详细信息和信息以获得您正在寻找的帮助。



If none of this steers you in the right direction, i would encourage you to use Improve Question link on your initial post to add more details and information to get the assistance you are looking for.


这篇关于如何从应用程序文件夹中删除图像并从数据库中删除文件名(图像名称)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆