문제

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();

(조금 늦었다. 얼마나 이상한 지.)

대상 폴더가 존재하는지 확인해야하므로 FTP 디렉토리를 작성하는 것이 복잡 할 수 있습니다. 디렉토리를 확인하고 만들려면 FTP 라이브러리를 사용해야 할 수도 있습니다. 당신은 이것을 볼 수 있습니다 : http://www.componentpro.com/ftp.net/ 그리고이 예 : http://www.componentpro.com/doc/ftp/creating-a-new-directory-synchronously.htm

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top