private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
if (DrawingRects.Count > 0)
{
// The last drawn shape
var dr = DrawingRects.Last();
if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
{
rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);
if (saveRectangles)
{
DirectoryInfo dInfo = new DirectoryInfo(@"d:\rectangles");
var files = GetFilesByExtensions(dInfo, ".bmp");
if (files.Count() > 0)
{
foreach (var f in files)
{
}
}
rectangleName = @"d:\Rectangles\rectangle" saveRectanglesCounter ".bmp";
FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
string json = JsonConvert.SerializeObject(
FileList,
Formatting.Indented // this for pretty print
);
using (StreamWriter sw = new StreamWriter(@"d:\rectangles\rectangles.txt", false))
{
sw.Write(json);
sw.Close();
}
rectImage.Save(rectangleName);
saveRectanglesCounter ;
}
pixelsCounter = rect.Width * rect.Height;
pictureBox1.Invalidate();
listBox1.DataSource = FileList.ToList();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
}
I'm using DirectoryInfo and the method GetFilesByExtensions
public IEnumerable<FileInfo> GetFilesByExtensions(DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
IEnumerable<FileInfo> files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
if there are existing files for example rectangle1.bmp rectangle2.bmp.....rectangle7.bmp then when creating a new rectangle file on the hard disk i want it to be rectangle8.bmp
now it's trying to create another rectangle1.bmp and give exception and i don't want to delete the existing files but to create new ones.
and make it as much as possible generic. but the main goal is to create new files names according to those existing and continue the counting.
CodePudding user response:
You can write a method that checks if the proposed name exists or not
string GetNextName(string baseName, string extension)
{
int counter = 1;
string nextName = baseName counter extension;
while(File.Exists(nextName))
{
counter ;
nextName = baseName counter extension;
}
return nextName;
}
and call it in this way:
rectangleName = GetNextName(@"d:\Rectangles\rectangle", ".bmp");
CodePudding user response:
You can use linq and do everything in one statement like this:
DirectoryInfo di = new DirectoryInfo(@"D:\rectangles");
var maxIndex = di.GetFiles().Select(fi => fi.Name.Replace("rectangle","").Replace(".bmp", "")).Max(i => i);