我是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 pictureBox - > 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);
}
答案 0 :(得分: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()
,也会发生这种情况。见这里:Does FileStream.Dispose close the file immediately?
答案 1 :(得分: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);
}
更新: 我更新了我的答案以反映您的最新答案。 有关详细信息,请转到this post
答案 2 :(得分:-1)
这样写 using(FileStream fs = new FileStream(name,FileMode.Create,FileAccess.Write))
} pictureBoxPictADUStudent.BackgroundImage = new Bitmap(name);