Skip to content

Instantly share code, notes, and snippets.

@Joooohee
Created September 20, 2024 13:41
Show Gist options
  • Save Joooohee/901ee96315ccd9830e69715e0fdda9b8 to your computer and use it in GitHub Desktop.
Save Joooohee/901ee96315ccd9830e69715e0fdda9b8 to your computer and use it in GitHub Desktop.
FTP서버 경로의 하위 경로 포함 전체 파일 리스트 가져오기
private void getFilesRecursively(string fullpath, string ftpUser, string ftpPw, DataTable dataTable)
{
var credentials = new NetworkCredential(ftpUser, ftpPw);
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(fullpath);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
listRequest.EnableSsl = true;
List<string> lines = new List<string>();
using (WebResponse listResponse = listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
while (!listReader.EndOfStream)
{
string line = listReader.ReadLine();
lines.Add(line);
}
}
foreach (string line in lines)
{
string[] tokens = line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
// 파일명
string name = tokens[3];
// 타입(폴더or파일)
string permissions = tokens[2];
// 재귀를 위한 경로 재정의  
string fileUrl = $"{fullpath}{name}";
// 폴더면 재귀함수 실행          
if (permissions == "<DIR>")
{
getFilesRecursively($"{fileUrl}/", ftpUser, ftpPw, dataTable);
}
else
{
// 파일생성일자                    
string creationDate = tokens[0];
// 파일생성시간
string creationTime = tokens[1];
// 일자+시간 타입으로 변경                 
string dateTimeString = $"{creationDate} {creationTime}";
DateTime parsedCreationDate = DateTime.ParseExact(dateTimeString, "MM-dd-yy hh:mmtt", CultureInfo.InvariantCulture);
DataRow row = dataTable.NewRow(); row["FILENAME"] = name;
row["CREATIONDATE"] = parsedCreationDate;
row["FULLPATH"] = fileUrl; dataTable.Rows.Add(row);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment