[英]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.