[英]How can I check if a file already exists?
public void SaveFormPicutreBoxToBitMapIncludingDrawings()
{
using (Bitmap b = new Bitmap(pictureBox1.Width, pictureBox1.Height))
{
pictureBox1.DrawToBitmap(b, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
string fn = @"d:\PictureBoxToBitmap\" + PbToBitmap.ToString("D6") + ".bmp";
if (File.Exists(fn))
{
}
else
{
b.Save(@"d:\PictureBoxToBitmap\" + PbToBitmap.ToString("D6") + ".bmp"); // to fix/repair give gdi error exception.
PbToBitmap++;
}
}
}
如果我将 trackBar 向右移动,它将保存第一个文件 000000.bmp,然后将其提高一个,下次它将保存文件 000001.bmp
但是,如果我现在向左移动一次,变量 fn 是 000002.bmp,它不存在,它将保存之前的图像,实际上是 000001.bmp。
当我向左移动时它应该做什么应该是 000001.bmp 看到它存在并且什么也不做。
如果不进行此检查,如果我将 trackBar 向右或向左移动,它将一直保存文件,所以几次后我将拥有超过 90 个几乎完全相同的文件。
变量 PbtoBitmap 是 Form1 顶部的 int 类型,我刚从 0 开始。 PbToBitmap = 0;
我所说的 trackBar 是 trackBar1,在滚动事件中我调用了这个 SaveFormPicutreBoxToBitMapIncludingDrawings 函数。
这是 trackBar1 滚动事件:
private void trackBar1_Scroll(object sender, EventArgs e)
{
currentFrameIndex = trackBar1.Value;
textBox1.Text = "Frame Number : " + trackBar1.Value;
wireObject1.woc.Set(wireObjectAnimation1.GetFrame(currentFrameIndex));
trackBar1.Minimum = 0;
trackBar1.Maximum = fi.Length - 1;
setpicture(trackBar1.Value);
pictureBox1.Refresh();
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
button8.Enabled = false;
SaveFormPicutreBoxToBitMapIncludingDrawings();
return;
}
目前尚不清楚您要完成什么,但您正在从计数器PbToBitmap
生成文件名。 这个计数器只会增加而不会减少,所以它当然会“继续保存文件……”。
如果您希望计数器与您所在的帧相匹配,请删除PbToBitmap
并在trackBar1_Scroll
调用内部:
string dir = @"d:\PictureBoxToBitmap";
SaveFormPictureBoxToBitMapIncludingDrawings(dir, currentFrameIndex);
将您的SaveFormPictureBoxToBitMapIncludingDrawings
更改为:
public void SaveFormPictureBoxToBitMapIncludingDrawings(string dir, int frameIndex)
{
string fn = Path.Combine(dir, frameIndex.ToString("D6") + ".bmp");
if (!File.Exists(fn))
{
using (Bitmap b = new Bitmap(pictureBox1.Width, pictureBox1.Height))
{
pictureBox1.DrawToBitmap(b, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
b.Save(fn);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.