Search code examples
c#imagedirectorymove

How to constantly rename a file and move it


I am trying to constantly rename and move an image to another folder. This folder is used for database so i am trying to store all the images inside this folder . Thus, i needed to rename each image constantly so they will not overwrite each other. (Some renaming convention : images.jpg, images1.jpg, images2.jpg)

I saw the move method but it doesn't let me constantly change the file name and maybe use a for loop to loop it. However, if i am going to detect if the images already exist and move on to a new name? ( Example : images1.jpg already exist but the program is going to replace it.)

Any idea how to work around this?


Solution

  • Use this:

    var files = new List<string>();
    
    foreach (var file in Directory.GetFiles(@"Your Location"))
    {
        var fileName = Path.GetFileNameWithoutExtension(file);
    
        if (fileName.StartsWith("Image"))
        {
            files.Add(fileName.Replace("Image",""));
        } 
    }
    
    var last = int.Parse(files.OrderByDescending(f => f.ToString()).First()) + 1;
    

    To get the next index available, then just move it to where ever you need