我有一个 ASP.NET (4.5) 网站。
下面的这个按钮命令将 employeename、employeelastname、employeephoto 插入图像文件夹并将图像路径插入数据库。
我希望图像路径自动为唯一名称 + 扩展名;
string filepath =//"uniquename"+ ext;
因此,EmployeeID 是唯一的,因此不会出现混淆或重复的照片。
我怎样才能做到这一点?
谢谢。
protected void Button1_Click(object sender, EventArgs e) //Insert
{
if (FileUploadControl.HasFile)
{
string ext = Path.GetExtension(FileUploadControl.FileName);
if (ext == ".jpg" || ext == ".png" || ext == ".jpeg" || ext == ".gif")
{
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (EmployeeFirstName, EmployeeLastName, EmployeePhotoPath) VALUES (@item1,@item2,@img)", cnn);
cmd.Parameters.AddWithValue("@item1", TextBox1.Text);
cmd.Parameters.AddWithValue("@item2", TextBox2.Text);
string filepath = //"uniquename" + ext;
FileUploadControl.SaveAs(Server.MapPath("Images/") + filepath);
cmd.Parameters.AddWithValue("@img", filepath);
cmd.ExecuteNonQuery();
cnn.Close();
Label3.Text = "successfully inserted";
}
catch (Exception ex)
{
Label3.Text = ex.Message;
}
temizle();
}
else
{
Label3.Text = "selected file is not a photo";
}
}
else
{
Label3.Text = "please upload employee photo";
}
}
}
最佳答案
如果您只需要文件名是唯一的,而您不一定关心它们的名称,一个简单的解决方案是为文件名使用 guid:
string filepath = Guid.NewGuid().ToString() + ext;
将员工姓名添加到文件名中可能也是一个好主意,这样仅通过查看文件名就可以更轻松地识别文件:
string filepath = string.Format("{0}-{1}-{2}{3}",
TextBox1.Text,
TextBox2.Text,
Guid.NewGuid().ToString(),
ext);
关于c# - 使图像路径唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19146585/