UFO ET IT

C #을 사용하여 FTP 서버에 디렉터리를 어떻게 생성합니까?

ufoet 2020. 11. 29. 12:40
반응형

C #을 사용하여 FTP 서버에 디렉터리를 어떻게 생성합니까?


C #을 사용하여 FTP 서버에 디렉터리를 만드는 쉬운 방법은 무엇입니까?

다음과 같이 기존 폴더에 파일을 업로드하는 방법을 알아 냈습니다.

using (WebClient webClient = new WebClient())
{
    string filePath = "d:/users/abrien/file.txt";
    webClient.UploadFile("ftp://10.128.101.78/users/file.txt", filePath);
}

나는에 업로드하려는 경우에는 users/abrien, 내가받을 WebException파일을 사용할 수없는 말을. 파일을 업로드하기 전에 새 폴더를 만들어야하지만 WebClient이를 수행 할 방법이없는 것 같습니다.


사용 FtpWebRequest하는 방법으로, WebRequestMethods.Ftp.MakeDirectory.

예를 들면 :

using System;
using System.Net;

class Test
{
    static void Main()
    {
        WebRequest request = WebRequest.Create("ftp://host.com/directory");
        request.Method = WebRequestMethods.Ftp.MakeDirectory;
        request.Credentials = new NetworkCredential("user", "pass");
        using (var resp = (FtpWebResponse) request.GetResponse())
        {
            Console.WriteLine(resp.StatusCode);
        }
    }
}

중첩 된 디렉토리를 생성하려는 경우 답은 다음과 같습니다.

폴더가 ftp에 있는지 확인하는 깨끗한 방법이 없으므로 한 번에 한 폴더 씩 모든 중첩 구조를 반복하고 만들어야합니다.

public static void MakeFTPDir(string ftpAddress, string pathToCreate, string login, string password, byte[] fileContents, string ftpProxy = null)
    {
        FtpWebRequest reqFTP = null;
        Stream ftpStream = null;

        string[] subDirs = pathToCreate.Split('/');

        string currentDir = string.Format("ftp://{0}", ftpAddress);

        foreach (string subDir in subDirs)
        {
            try
            {
                currentDir = currentDir + "/" + subDir;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(currentDir);
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(login, password);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                //directory already exist I know that is weak but there is no way to check if a folder exist on ftp...
            }
        }
    }

이 같은:

// remoteUri points out an ftp address ("ftp://server/thefoldertocreate")
WebRequest request = WebRequest.Create(remoteUri);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
WebResponse response = request.GetResponse();

(조금 늦었습니다. 얼마나 이상합니다.)


Creating an FTP directory might be complicated since you have to check if the destination folder exists or not. You may need to use an FTP library to check and create a directory. You can take a look at this one: http://www.componentpro.com/ftp.net/ and this example: http://www.componentpro.com/doc/ftp/Creating-a-new-directory-Synchronously.htm

참고URL : https://stackoverflow.com/questions/860638/how-do-i-create-a-directory-on-ftp-server-using-c

반응형