2

我是 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);
        }
4

3 回答 3

4

您在此处打开文件:

using (FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write))
                                   // ^^^^ This is your filename..

..Bitmap并且还试图打开文件来阅读它..这里:

pictureBoxPictADUStudent.BackgroundImage = new Bitmap(name);
                                                   // ^^^^ You are using it again here

Bitmap您写入文件时将无法从文件中读取..

编辑:

正如评论中指出的那样,即使fs.Dispose()正在调用,也可能发生这种情况。请参见此处:FileStream.Dispose 是否立即关闭文件?

于 2013-01-31T11:34:37.670 回答
0

这里的问题是文件被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);
        } 

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

于 2013-01-31T11:43:27.623 回答
-1

像这样使用 (FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write)) 编写

{


} pictureBoxPictADUStudent.BackgroundImage = new Bitmap(name);

于 2013-01-31T11:44:44.013 回答