Nice programing

FtpWebRequest 전에 FTP에 파일이 있는지 확인하는 방법

nicepro 2020. 11. 14. 11:08
반응형

FtpWebRequest 전에 FTP에 파일이 있는지 확인하는 방법


내가 사용할 필요가 FtpWebRequestFTP를 디렉토리에 파일을 넣어. 업로드하기 전에 먼저이 파일이 있는지 알고 싶습니다.

이 파일이 있는지 확인하려면 어떤 방법이나 속성을 사용해야합니까?


var request = (FtpWebRequest)WebRequest.Create
    ("ftp://ftp.domain.com/doesntexist.txt");
request.Credentials = new NetworkCredential("user", "pass");
request.Method = WebRequestMethods.Ftp.GetFileSize;

try
{
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
    FtpWebResponse response = (FtpWebResponse)ex.Response;
    if (response.StatusCode ==
        FtpStatusCode.ActionNotTakenFileUnavailable)
    {
        //Does not exist
    }
}

일반적으로 이와 같은 코드의 기능에 예외를 사용하는 것은 좋지 않지만이 경우에는 실용주의를위한 승리라고 생각합니다. 디렉토리의 호출 목록은 이런 방식으로 예외를 사용하는 것보다 훨씬 비효율적 일 수 있습니다.

그렇지 않다면 좋은 습관이 아니라는 점만 알아 두세요!

편집 : "그것은 나를 위해 작동합니다!"

이것은 대부분의 ftp 서버에서 작동하는 것처럼 보이지만 전부는 아닙니다. 일부 서버는 SIZE 명령이 작동하기 전에 "TYPE I"을 보내야합니다. 다음과 같이 문제가 해결되어야한다고 생각했을 것입니다.

request.UseBinary = true;

불행히도 FtpWebRequest가 파일을 다운로드하거나 업로드하지 않는 한 "TYPE I"을 보내지 않는 것은 설계상의 제한 (큰 버그!)입니다. 여기에서 토론 및 Microsoft 응답을 참조 하십시오 .

대신 다음 WebRequestMethod를 사용하는 것이 좋습니다. 이것은 파일 크기를 반환하지 않는 서버에서도 테스트 한 모든 서버에서 작동합니다.

WebRequestMethods.Ftp.GetDateTimestamp

때문에

request.Method = WebRequestMethods.Ftp.GetFileSize

경우에 따라 실패 할 수 있습니다 (550 : ASCII 모드에서는 SIZE가 허용되지 않음). 대신 타임 스탬프를 확인할 수 있습니다.

reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password);
reqFTP.UseBinary = true;
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;

FtpWebRequest(.NET의 다른 클래스도) 파일 ​​존재를 확인하는 명시적인 방법이 없습니다. 당신은 같은 요청을 남용 할 필요 GetFileSizeGetDateTimestamp.

string url = "ftp://ftp.example.com/remote/path/file.txt";

WebRequest request = WebRequest.Create(url);
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
    request.GetResponse();
    Console.WriteLine("Exists");
}
catch (WebException e)
{
    FtpWebResponse response = (FtpWebResponse)e.Response;
    if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
    {
        Console.WriteLine("Does not exist");
    }
    else
    {
        Console.WriteLine("Error: " + e.Message);
    }
}

보다 간단한 코드를 원하면 타사 FTP 라이브러리를 사용하십시오.

예를 들어 WinSCP .NET 어셈블리의 경우 해당 Session.FileExists방법을 사용할 수 있습니다 .

SessionOptions sessionOptions = new SessionOptions {
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "username",
    Password = "password",
};

Session session = new Session();
session.Open(sessionOptions);

if (session.FileExists("/remote/path/file.txt"))
{
    Console.WriteLine("Exists");
}
else
{
    Console.WriteLine("Does not exist");
}

(I'm the author of WinSCP)


I use FTPStatusCode.FileActionOK to check if file exists...

then, in the "else" section, return false.

참고URL : https://stackoverflow.com/questions/347897/how-to-check-if-file-exists-on-ftp-before-ftpwebrequest

반응형