Ant*_*ien 61 .net c# ftp webclient
使用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);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想上传到users/abrien,我会WebException说文件不可用.我认为这是因为我需要在上传文件之前创建新文件夹,但WebClient似乎没有任何方法可以实现.
Jon*_*eet 104
使用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Yan*_*ard 34
如果要创建嵌套目录,可以使用以下答案
没有干净的方法来检查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...
}
}
}
Run Code Online (Sandbox Code Playgroud)
Fre*_*örk 20
像这样的东西:
// remoteUri points out an ftp address ("ftp://server/thefoldertocreate")
WebRequest request = WebRequest.Create(remoteUri);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
WebResponse response = request.GetResponse();
Run Code Online (Sandbox Code Playgroud)
(有点晚了.多奇怪.)