입력받은 경로 및 파일명으로 시작하는 모든 파일 삭제

files 라는 폴더에

회계-1.doc,

회계-2.doc,

회계-3.doc,

회계-4.doc,

안회계-1.doc,

노회계-1.doc,

회계아님.doc

라는 파일이 있을 때, 파일명이 "회계"로 시작하는 모든 파일을 한번에 삭제해주는 로직입니다.

 

호출하는 방법은

 

string sReturn = string.Empty;

int i = deleteFile("/files/회계", out  sReturn);

 

sReturn 스트링 변수를 out 파라미터로 받는 이유는 혹시 파일 삭제 중 에러가 발생했을 때 에러메세지를 받아오기 위함입니다.

함수 실행이 끝나면 i에는 결과값이 들어가며

-1이면 삭제 실패 (이 때 sReturn을 찍어보면 에러 메세지를 확인할 수 있음)

0이면 한 건도 삭제되지 않음

1이상이면 삭제한 파일 건수를 리턴합니다.

 

/// <summary>
/// 첨부파일 삭제
/// </summary>
/// <param name="sFile">첨부파일경로+파일명</param>
/// <param name="sReturn">리턴텍스트 : 성공할경우 빈 값, 실패할경우 오류메세지를 리턴한다.</param>
/// <returns>-1 : 삭제 실패, 0 :  삭제건 없음, 1이상 : 삭제건수</returns>
public int deleteFileFunc(string sFile, out string sReturn)
{
    string sDirPath = string.Empty;
    string sFileName = string.Empty;
    int iReturn = 0;

    //파일경로+파일명 파라미터가 없을 경우 리턴
    if (sFile == "")
    {
        sReturn = "";
        return 0;
    }

    try
    {
        sFile = Server.MapPath(sFile);
        sDirPath = Path.GetDirectoryName(sFile);
        sFileName = Path.GetFileName(sFile);

        //입력받은 파일경로가 존재하지 않을 경우 리턴
        if (!Directory.Exists(sDirPath))
        {
            sReturn = "존재하지 않는 경로입니다.";
            return -1;
        }

        //파일경로가 존재할 경우 해당 경로에 있는 파일 갯수만큼 돌면서 입력받은 파일명 파라미터와 같은 글자로 시작하는 항목을 삭제함
        int iCnt = Directory.GetFiles(sDirPath).Length;
        string sCurrFileNM = string.Empty;

        if (iCnt > 0)
        {
            string[] aFileNM = Directory.GetFiles(sDirPath);

            for (int i = 0; i < aFileNM.Length; i++)
            {
                sCurrFileNM = Path.GetFileName(aFileNM[i].ToString()).Substring(0, sFileName.Length);
                       
                if (sCurrFileNM == sFileName)
                {
                    File.Delete(aFileNM[i].ToString());
                    iReturn++;
                }
            }
        }

        sReturn = "";
        return iReturn;
    }
    catch (Exception ex)
    {
        sReturn = ex.Message;
        return -1;
    }
}

 

중간 부분에 해당 경로의 전체 파일을 배열에 넣는 부분이 있는데, 그걸 안해주면 for문 도중 파일이 삭제되면서 해당 인덱스를 찾아가지 못하기 때문에 i _ i ... 미리 배열에 전체 파일명을 넣어놓고 시작한다.

prev 1 2 3 4 5 6 7 ··· 66 next