这是我的一段代码,我想删除一个文件(第 12 行)。
但是出现了一个错误:项目无法访问该文件,因为它正被 c# 中的另一个进程恰好在 while 循环的第二次使用。我处理并关闭了每个对象。
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);
}