如何在存储到数据库后重命名图像?我已尝试使用System.IO.File.Move(oldpath, newpath)
,但我收到了错误
'System.IO.IOException'
Additional information: The process cannot access the file because it is being used by another process.
还有其他办法吗?
这是我的代码
byte[] imageID = null;
FileStream fstream = new FileStream(this.pathID.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageID = br.ReadBytes((int)fstream.Length);
string login = "server=localhost;database=id;uid=root;password=root;";
MySqlConnection conn = new MySqlConnection(login);
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO picture(`Picture_Employee`) VALUES (@EMP);";
cmd.Parameters.AddWithValue("@EMP", imageID);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Picture Added");
//sampleID.Text contains ID# of Employee and label1.Text contains the name of the employee
string newpath = sampleID.Text + "-" + label1.Text;
System.IO.File.Move(pathID.Text, newpath);
将图像存储到数据库后,我希望它将其重命名为ID#-EmployeeName
答案 0 :(得分:0)
正如其他人所指出的,您应该关闭FileStream
,类似于关闭数据库的方式。
事件更好,因为这些都实现了IDisposable
界面,您可以使用C#的using
语句来调用Dispose
(内部自动调用Close()
):
byte[] imageID = null;
using (FileStream fstream = new FileStream(this.pathID.Text, FileMode.Open, FileAccess.Read))
{
BinaryReader br = new BinaryReader(fstream);
imageID = br.ReadBytes((int)fstream.Length);
string login = "server=localhost;database=id;uid=root;password=root;";
using (MySqlConnection conn = new MySqlConnection(login))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO picture(`Picture_Employee`) VALUES (@EMP);";
cmd.Parameters.AddWithValue("@EMP", imageID);
cmd.ExecuteNonQuery();
MessageBox.Show("Picture Added");
}
//sampleID.Text contains ID# of Employee and label1.Text contains the name of the employee
string newpath = sampleID.Text + "-" + label1.Text;
System.IO.File.Move(pathID.Text, newpath);
请注意,我删除了conn.Close()
,因为using
语句会为您处理此问题。
答案 1 :(得分:0)
您需要关闭文件流。因为您从未关闭它,它仍然在使用,操作系统无法移动文件。您可以通过调用流对象上的Close()
来执行此操作:
fstream.Close()
请参阅我在您的问题上发布的有关最佳做法的评论,以确保您在执行类似任务时不会遇到类似问题。