Question

How do you rename an image after storing in a database? I already tried using System.IO.File.Move(oldpath, newpath) but I'm getting an error

'System.IO.IOException' Additional information: The process cannot access the file because it is being used by another process.

Is there any other way to do this?

Here's my code

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);

After storing the image to the database I want it to rename it as ID#-EmployeeName

Was it helpful?

Solution

As others have pointed out, you should close the FileStream similar to how you're closing the database.

Event better, since these both implement the IDisposable interface you can use C#'s using statement to call Dispose (which internally calls Close() automatically):

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);

Notice that I removed conn.Close() as the using statement will handle this for you.

OTHER TIPS

You need to close the file stream. Because you never close it, it is still in use and the operating system is unable to move the file. You can do this by calling Close() on the stream object:

fstream.Close()

See the comments I posted on your question regarding best practices to ensure that you won't run into issues like this when performing similar tasks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top