【发布时间】:2011-07-23 06:35:51
【问题描述】:
好的,新问题这是我的完整代码,我将解释我正在尝试做的事情并分割每个部分,以便您可以看到我想要实现的目标:
完整代码:
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
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(Convert.ToString(reader[0])))
{
System.IO.File.Delete(Convert.ToString(reader[0]));
}
}
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId +
"/uploadedimage/") +
Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "','" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
好的,我要做的第一部分是选择与用户 ID 相关的图片路径,然后如果用户 ID 与我尝试上传的用户 ID 相同,则删除存在的文件(未存储在数据库中,因此 IO ) 这部分不起作用当前用户标识的文件路径名没有被删除。
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(Convert.ToString(reader[0])))
{
System.IO.File.Delete(Convert.ToString(reader[0]));
}
}
第二部分只是将新的文件上传路径和名称插入到与当前用户 ID 相关的我的数据库中(这有效),文件被上传到正确的文件夹并插入到我的数据库中。我可以将其更改为 UPDATE 而不是插入,但 atm 要么或不挑剔。
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId +
"/uploadedimage/") +
Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "','" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
所以我的问题是为什么我的 if 语句没有删除我数据库中当前保存的当前图像路径的记录?所发生的只是我的新图像被上传到同一个文件夹中,但旧图像仍然存在?
请记住,虽然我并没有尝试删除“相同”文件名,但简单的 saveas 会覆盖它已经在我的代码中,我需要的是让我的代码删除当前在用户 ID 特定文件夹中的任何图像当我尝试保存新图片上传时。
对代码有什么帮助吗?
谢谢大家
【问题讨论】:
-
重读这篇文章很难说明我试图解释的内容希望任何有经验的程序员都能理解我在做什么:) 抱歉我能用最好的方式解释它的混乱
-
你试过调试这段代码吗?有趣的是 while 循环内的 if 块。有些东西告诉我 FileExists 失败了。
-
是的,或者文件删除,因为我正在删除的路径名是这样的:
~/userdata/2/uploadedimage/batman-for-facebook.jpg我尝试调试但没有任何报告 -
路径是这样存储在数据库中的吗?如果是这样,您需要将其从相对 URL 转换为文件系统地址。
-
是的,它以这种方式存储,我将如何转换它?在哪里?