C# 检查目录中是否存在多个文件

C# 检查目录中是否存在多个文件,c#,C#,每次上传者剪切图像时,我都会保存一个新图像,我想检查每个新图像是否存在。我有以下代码: private void pictureBox5_MouseUp(object sender, MouseEventArgs e) { Selecting = false; // Copy the selected area. SelectedArea = GetSelectedArea(pictureBox5.Imag

每次上传者剪切图像时,我都会保存一个新图像,我想检查每个新图像是否存在。我有以下代码:

private void pictureBox5_MouseUp(object sender, MouseEventArgs e)
        {
            Selecting = false;

            // Copy the selected area.
            SelectedArea = GetSelectedArea(pictureBox5.Image, Color.Transparent, Points);

            SelectedArea.Save(@"C:\Users\User\Desktop\Gallery\image1cropped.png", ImageFormat.Png);


        }
我希望它能像image2cropped,image3cropped一样保存。。并检查它是否存在

if(File.Exists(@"C:\Users\User\Desktop\Gallery\image1cropped.png", ImageFormat.Png);
我想让它像图像2被截取,图像3被截取一样检查。。等等
想法?

如果我理解的话:您正在将一个区域保存到一个文件中。第一次,您将其保存到image1cropped.png,然后您希望自动使用image2cropped以避免覆盖第一个文件,对吗? 在这种情况下,您可以使用以下代码:

        int i = 0; // set 0 to start at 1 for "image1cropped"
        string freeFileName; // the final fileName that doesn't exist

        // loop while file imageXcropped exists
        do
        {
            i++;
            freeFileName = @"C:\Users\User\Desktop\Gallery\image" + i + "cropped.png";
        } while (File.Exists(freeFileName));

        // at this point freeFileName doesn't exists, you can use it
        // use : SelectedArea.Save(freeFileName, ImageFormat.Png);

是的,我解决了这个问题。但我想检查它们是否存在,是同一个算法吗?别管我解了它。这是我最后的代码:SelectedArea.Save(@“C:\Users\User\Desktop\Gallery\image”+NumberOfClick.ToString()+“crapped.png”,ImageFormat.png);字符串文件名=@“C:\Users\User\Desktop\Gallery\image”+NumberOfClick.ToString()+“cropped.png”;如果(File.Exists(filename)){button1.Visible=true;pictureBox5.Visible=false;}是否要在保存前检查它以不覆盖它,还是在保存后检查它以确保文件保存良好?因此,您要在保存后检查文件是否存在。。。我不确定这是否必要,因为我认为如果无法保存文件,.save方法将引发异常!使用algo,当应用程序重新启动时,youNumberOfClick将被重置,然后Image1croped将被覆盖。这是你想要的吗?请注意,在您的情况下,“.toString()”是可选的;)