[ASP.NET] StandardControl : FileUpload (싸이즈 확인, 중복파일처리)
================================================
FrmFileUploadWithFileNumber.aspx
================================================
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmFileUploadWithFileNumber.aspx.cs" Inherits="FrmFileUploadWithFileNumber" %>
================================================
FrmFileUploadWithFileNumber.aspx.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class FrmFileUploadWithFileNumber : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string strDirectory = Server.MapPath("~/Icons") + "\\";
//[1] 파일이 첨부되었다면
if (txtGroupIcon.HasFile)
{
long ll_FileLength = txtGroupIcon.PostedFile.ContentLength;
if (ll_FileLength > 1048576)
{
this.lblResult.Text = "1M 이하 용량만 업로드 가능합니다.";
}
else
{
//[2] App_Data 폴더로 파일 업로드
// txtGroupIcon.SaveAs(Server.MapPath("~/")+ "\\Icons\\" + txtGroupIcon.FileName);
string ls_FileName = GetFileNameWithNumbering(strDirectory, txtGroupIcon.FileName);
txtGroupIcon.SaveAs( Path.Combine(strDirectory, ls_FileName) );
this.lblResult.Text = ls_FileName + "파일이 업로드 되었습니다.";
}
}
}
#region 중복된 파일명 뒤에 번호 붙이는 메서드 : GetFileNameWithNumbering
///
/// GetFilePath : 파일명 뒤에 번호 붙이는 메서드
///
/// 경로(c:\MyFiles)
/// Test.txt
/// Test(1).txt
private string GetFileNameWithNumbering(string strBaseDirTemp, string strFileNameTemp)
{
string strName = //순수파일명 : Test
Path.GetFileNameWithoutExtension(strFileNameTemp);
string strExt = //확장자 : .txt
Path.GetExtension(strFileNameTemp);
bool blnExists = true;
int i = 0;
while (blnExists)
{
//Path.Combine(경로, 파일명) = 경로+파일명
if (File.Exists(Path.Combine(strBaseDirTemp, strFileNameTemp)))
{
strFileNameTemp =
strName + "(" + ++i + ")" + strExt;//Test(3).txt
}
else
{
blnExists = false;
}
}
return strFileNameTemp;
}
#endregion
}