본문 바로가기

Programming/ASP .NET

파일 업로드 소스

주의 : FileUpload 컴퍼넌트 추가 후 사용
참고 : 같은 이름의 파일이 존재할 경우 "filename_x.ext" 형식으로 파일을 업로드 함

========= 파일 업로드 ==========
        if (FileUpload1.HasFile)
        {
            string upDir = "E:\\Study\\Web\\EmsClient\\Upload\\";
            DirectoryInfo di = new DirectoryInfo(upDir);
            if (!di.Exists)
                di.Create();

            string fName = FileUpload1.FileName;
            string fFullName = upDir + fName;

            FileInfo fInfo = new FileInfo(fFullName);
            if (fInfo.Exists)
            {

                int fIndex = 0;
                string fExtension = fInfo.Extension;
                string fRealName = fName.Replace(fExtension, "");

                string newFileName = "";
                do
                {
                    fIndex++;
                    newFileName = fRealName + "_" + fIndex.ToString() + fExtension;
                    fInfo = new FileInfo(upDir + newFileName);
                } while (fInfo.Exists);

                fFullName = upDir + newFileName;
            }

            FileUpload1.PostedFile.SaveAs(fFullName);
            Label1.Text = "업로드 된 파일 : " + fFullName;
        }
        else
        {
            Label1.Text = "업로드 된 파일이 존재하지 않습니다.";
        }