どのように私は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();
(少し遅れて。どのように奇妙な。)
FTPディレクトリを作成しますが、先のフォルダが存在するかどうかをチェックする必要があるため複雑になるかもしれません。あなたはチェックして、ディレクトリを作成するFTPライブラリを使用する必要があるかもしれません。あなたはこの1を見てとることができます。 http://www.componentpro.com/ftp.net/ >この例:のhttp:// WWW。 componentpro.com/doc/ftp/Creating-a-new-directory-Synchronously.htmする
所属していません StackOverflow