2

私はC#プログラミングの初心者です。を使用しているときに問題がありFileStreamます。データベース内の人物のIDを検索して、データベースから写真を取得したい。そしてそれは動作します!!。しかし、その人の写真を2回取得しようとすると(同じIDを2回挿入します)。それは 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 = 新しいビットマップ(名前);

于 2013-01-31T11:44:44.013 に答える