我是C#编程的新手。我在使用FileStream时遇到问题。我想通过在数据库中搜索人的ID从数据库中检索图片。和它的工作!但是当我尝试两次检索该人的照片时(两次插入相同的ID)。它会给IOException

"The process cannot access the file 'C:\Users\dor\Documents\Visual Studio 2010\Projects\studbase\studbase\bin\Debug\foto.jpg' because it is being used by another process."


我有1个按钮-> buttonLoad |
       1张图片框-> pictureBoxPictADUStudent

这是buttonLoad上的代码

        string sql = "SELECT Size,File,Name FROM studgeninfo WHERE NIM = '"+textBoxNIM.Text+"'";
        MySqlConnection conn = new MySqlConnection(connectionSQL);
        MySqlCommand comm = new MySqlCommand(sql, conn);

        if (textBoxNIM.Text != "")
        {
            conn.Open();
            MySqlDataReader data = comm.ExecuteReader();

            while (data.Read())
            {

                int fileSize = data.GetInt32(data.GetOrdinal("size"));
                string name = data.GetString(data.GetOrdinal("name"));


                using (FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write))
                {
                        byte[] rawData = new byte[fileSize];
                        data.GetBytes(data.GetOrdinal("file"), 0, rawData, 0, fileSize);
                        fs.Write(rawData, 0, fileSize);
                        fs.Dispose();
                        pictureBoxPictADUStudent.BackgroundImage = new Bitmap(name);
                }
            }

            conn.Close();
        }

        else
        {
            MessageBox.Show("Please Input Student NIM ", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

最佳答案

这里的问题是文件被new Bitmap()锁定。因此,您必须确保在加载位图后,就将其锁定在文件上了:

        using (FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write))
        {
                byte[] rawData = new byte[fileSize];
                data.GetBytes(data.GetOrdinal("file"), 0, rawData, 0, fileSize);
                fs.Write(rawData, 0, fileSize);
        }

        using (var bmpTemp = new Bitmap(name))
        {
            pictureBoxPictADUStudent.BackgroundImage= new Bitmap(bmpTemp);
        }


更新:
我更新了答案以反映您的最新答案。
有关更多详细信息,请转到this post

关于c# - 文件正在被另一个进程使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14624743/

10-14 16:40
查看更多