개발노트/C#

[C#] 폴더 내 동일한 파일명 존재할 경우, 파일명 순번처리

lovvepearl 2024. 3. 19. 16:55

 

//using System;
//using System.IO;
//using System.Collections.Generic;

//폴더 내 동일한 파일명 존재하는 경우, 파일명 순번처리

string title = {파일명};
string path = {폴더경로};

string[] files = Directory.GetFiles(path);

//순번표기한 파일명 내 순번 리스트화
List<int> orderList = new List<int> (); 
foreach(string file in files) {
    string fileName = Path.GetFileName(file);
    if(fileName.Contains(title+"_")) { //순번표기한 파일이 존재하는 경우
    	//기존 순번 추출하여 다음 순번지정
        int order = Convert.ToInt32(fileName.Split("_")[2].Replace(".pdf","")); 
        orderList.Add(order);
    }
}
//리스트에 값이 존재하는 경우 최대값 추출
int max = 0;
if(orderList.Any()) {
    max = orderList.Max();
}

string NewfileName = "";
//동일한 파일명 미존재하는 경우
if(Array.IndexOf(files, title) != -1 ){
    NewfileName = title + ".pdf";
} else {
    foreach(string file in files) {
        string fileName = Path.GetFileName(file);
        string targetName = "";
        if(max != 0){
            targetName = title + "_" + Convert.ToString(max);
        }
        if(fileName.Split(".")[0].Equals(title)) { //동일한 파일명 존재하는 경우
            string reName = fileName.Split(".")[0]+"_1.pdf"; //기존파일명 변경
            File.Move(file, Path.Combine(path, reName));
            NewfileName = fileName.Split(".")[0]+"_2.pdf";
            break;
        } else if(fileName.Contains(targetName)) { //순번표기한 파일이 존재하는 경우
            NewfileName = fileName.Replace(Convert.ToString(max), Convert.ToString(max+1));
            break;
        } else {
            NewfileName = title + ".pdf";
        }

    }
}

return NewfileName;