这是我的一段代码,我想删除一个文件(第12行)。
但是一个错误引发:项目无法访问该文件,因为在#循环的第二次中c#中的另一个进程正在使用它。我处理并关闭了每一个 对象
while (true)
{
string strEncrypted;
int strLenght = 0;
byte[] cryptedRGB;
string imgCamFile = Environment.CurrentDirectory + "\\___imgCam\\_sentImg\\__empImg.bmp";
if (File.Exists(@imgCamFile))
{
lock (@imgCamFile)
{
//if (camPictureBox.Image != null)
// camPictureBox.Image.Dispose();
GC.Collect();
System.IO.File.Delete(@imgCamFile);
GC.Collect();
}
}
strDataType = System.Text.Encoding.UTF8.GetBytes("Frame");
strEncrypted = clsCryption.Encrypt("Frame");
strDataType = new byte[strEncrypted.Length];
foreach (char c in strEncrypted.ToCharArray())
{
strDataType[strLenght] = (byte)c;
strLenght++;
}
if (optClient.Checked == true)
mClient.Send(strDataType);
else if (optServer.Checked == true)
mServerHandler.Send(strDataType);
MemoryStream Ms = new MemoryStream();
camPictureBox.Image.Save(Ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] mData = Ms.GetBuffer();
Ms.Close();
Ms.Dispose();
FileStream fileStream = new FileStream(imgCamFile, FileMode.Create, FileAccess.Write);
fileStream.Write(mData, 0, mData.Length);
fileStream.Close();
fileStream.Dispose();
Bitmap bitmap = new Bitmap(imgCamFile);
Size mS = bitmap.Size;
string[,] RGB = new string[mS.Width * 3, mS.Height];
int realWodth = mS.Width * 3;
byte[] myRGB = new byte[realWodth * mS.Height];
int cCounter = 0;
int pRow = 0;
for (int y = 0; y < mS.Height; y++)
{
cCounter = 0;
for (int x = 0; x < mS.Width; x++)
{
Color pixColor = bitmap.GetPixel(x, y);
RGB[cCounter, y] = pixColor.R.ToString(); ++cCounter;
RGB[cCounter, y] = pixColor.G.ToString(); ++cCounter;
RGB[cCounter, y] = pixColor.B.ToString(); ++cCounter;
myRGB[pRow] = Byte.Parse(pixColor.R.ToString()); pRow++;
myRGB[pRow] = Byte.Parse(pixColor.G.ToString()); pRow++;
myRGB[pRow] = Byte.Parse(pixColor.B.ToString()); pRow++;
}
}
int sent;
if (optClient.Checked == true)
sent = SendVarData(mClient, myRGB);
else if (optServer.Checked == true)
sent = SendVarData(mServerHandler, myRGB);
System.Threading.Thread.Sleep(4000);
}
答案 0 :(得分:0)
我认为这是问题:
Bitmap bitmap = new Bitmap(imgCamFile);
您永远不会将位图设置为null,以便在路径上保持锁定。
答案 1 :(得分:0)
请记住,这不是必需的:
Ms.Close();
Ms.Dispose();
fileStream.Close();
fileStream.Dispose();
因为dispose隐式调用close。
使用Bitmap类后释放资源:
Bitmap bitmap = new Bitmap(imgCamFile);
bitmap.Dispose();
答案 2 :(得分:0)
为什么要执行所有步骤? Image -> MemoryStream -> FileStream -> BitMap
Bitmap
是Image
- 您确定camPictureBox.Image
不是Bitmap
,而您无法用它进行计算吗?
如果没有......
using(var bitmap = new Bitmap(camPictureBox.Image))
{
// do your calculations
}
......或......
using (var ms = new MemoryStream())
{
camPictureBox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
using (var bitmap = new Bitmap(ms))
{
// do your work
}
}