[TIL] C# WPF : October 14, 2020

RE_BROTHER·2020년 10월 15일
0

TIL

목록 보기
26/41
post-thumbnail

C# WPF

File download & rename

Selenium 패키지를 업무 자동화 시스템 개발에 사용중인데, 데이터 시트를 다운받는 과정에서 데이터 시트 구분을 위해 파일명 변경이 필요하다.
다운로드 받은 파일을 자체적으로 Rename해주는 기능은 Selenium에서 지원되지 않는 것으로 보이며, 해당 이슈는 자체적으로 처리해야겠다.
데이터가 저장되는 Default directory를 Fix한 상태로 해당 directory에서 가장 마지막에 수정된 파일의 이름을 변경해볼까 한다.
File Search에는 System.IO 패키지를 사용한다.

public void lastFile_search(string title)
{
    // init part
    var files = new DirectoryInfo(driver_download_path).GetFiles("*.xls");
    string latestFile = "";
    DateTime lastUpdated = DateTime.MinValue;
    
    // search part
    foreach (FileInfo file in files)
    {
        if (file.LastWriteTime > lastUpdated)
        {
            lastUpdated = file.LastWriteTime;
            latestFile = file.Name;
        }
        // log part
        Console.WriteLine("Last File is " + latestFile);
    }
 }

Error

마지막에 생성된 파일만 logging하는 것이 아니라 모든 파일을 logging하는 상황이 벌어졌다.

Solution

foreach문 내에 Console.WriteLine를 사용해서 벌어진 일이다.

    foreach (FileInfo file in files)
    {
        if (file.LastWriteTime > lastUpdated)
        {
            lastUpdated = file.LastWriteTime;
            latestFile = file.Name;
        }
    }
    // log part
    Console.WriteLine("Last File is " + latestFile);

위와 같이 Console.WriteLineforeach문 밖으로 꺼냈더니 문제없이 실행된다.

Next

마지막에 생성된 파일을 찾았으니 해당 파일을 수정하는 Function만 정의를 하면 완성이다.
File Search에 사용했던 System.IO 패키지의 하위 패키지인 System.IO.File.Move 패키지를 사용하여 파일명을 직접적으로 바꾸는 것이 아닌 파일 이동을 통해 이름을 변경한다.
파일 이동을 위해서는 해당 파일의 절대 경로가 필요하다. 이미 파일의 절대 경로는 driver_download_path로 지정해놓았기에 작업에 귀찮은 점은 많이 덜었다.

C# Latest File Search & Rename Code

public void lastFile_Rename(string title)
{
    //string Folder = driver_download_path;
    var files = new DirectoryInfo(driver_download_path).GetFiles("*.xls");
    string latestFile = "";

    DateTime currentTime = DateTime.Now;

    // for rename_file
    string file_yyyymmdd = currentTime.ToString("yyyyMMdd");
    string file_hhmmss = currentTime.ToString("HHmmss");
    string rename_file = driver_download_path + title + "_" + file_yyyymmdd + "_" + file_hhmmss + ".xls";

    DateTime lastUpdated = DateTime.MinValue;
    
    // search latest file name
    foreach (FileInfo file in files)
    {
        if (file.LastWriteTime > lastUpdated)
        {
            lastUpdated = file.LastWriteTime;
            latestFile = file.Name;
        }
    }

    // set a target file path
    string origin_file = driver_download_path + latestFile;

    // launch rename
    System.IO.File.Move(origin_file, rename_file);

    //Console.WriteLine("Test : " + latestFile);
    //Console.WriteLine(title);
}

Values in Code

string file_yyyymmdd : 파일 이름 구분을 위해 현재 날짜를 yyyy-mm-dd 식으로 지정
string file_hhmmss : 파일 이름 구분을 위해 현재 시간을 hh-mm-ss 식으로 지정
string rename_file : 최종적으로 바꿔지는 파일 이름과 절대경로
string origin_file : 이름을 바꿀 파일의 이름과 절대경로

profile
I hope the All-Rounder Developer & Researcher

0개의 댓글