我想删除 FTP 中的文件夹。
对象可以FTPClient
删除吗?
要删除空目录,请使用以下RemoveDirectory
“方法” FtpWebRequest
:
void DeleteFtpDirectory(string url, NetworkCredential credentials)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.RemoveDirectory;
request.Credentials = credentials;
request.GetResponse().Close();
}
像这样使用它:
string url = "ftp://ftp.example.com/directory/todelete";
NetworkCredential credentials = new NetworkCredential("username", "password");
DeleteFtpDirectory(url, credentials);
尽管它变得更加复杂,但如果您需要删除一个非空目录。不支持FtpWebRequest
类中的递归操作(或 .NET 框架中的任何其他 FTP 实现)。您必须自己实现递归:
棘手的部分是从子目录中识别文件。没有办法以便携的方式使用FtpWebRequest
. 不幸的FtpWebRequest
是不支持该MLSD
命令,这是在 FTP 协议中检索具有文件属性的目录列表的唯一可移植方式。另请参阅检查 FTP 服务器上的对象是文件还是目录。
您的选择是:
LIST
命令 =ListDirectoryDetails
方法)并尝试解析特定于服务器的列表。许多 FTP 服务器使用 *nix 样式的列表,您可以通过d
条目开头的 来标识目录。但是许多服务器使用不同的格式。以下示例使用这种方法(假设 *nix 格式)。static void DeleteFtpDirectory(string url, NetworkCredential credentials)
{
var listRequest = (FtpWebRequest)WebRequest.Create(url);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
List<string> lines = new List<string>();
using (var listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (var listReader = new StreamReader(listStream))
{
while (!listReader.EndOfStream)
{
lines.Add(listReader.ReadLine());
}
}
foreach (string line in lines)
{
string[] tokens =
line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
string name = tokens[8];
string permissions = tokens[0];
string fileUrl = url + name;
if (permissions[0] == 'd')
{
DeleteFtpDirectory(fileUrl + "/", credentials);
}
else
{
var deleteRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
deleteRequest.Credentials = credentials;
deleteRequest.GetResponse();
}
}
var removeRequest = (FtpWebRequest)WebRequest.Create(url);
removeRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
removeRequest.Credentials = credentials;
removeRequest.GetResponse();
}
使用与之前的(平面)实现相同的方式。
或者使用支持递归操作的 3rd 方库。
例如,使用WinSCP .NET 程序集,您可以通过一次调用来删除整个目录Session.RemoveFiles
:
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Delete folder
session.RemoveFiles("/directory/todelete").Check();
}
MLSD
如果服务器支持,WinSCP 在内部使用该命令。如果没有,它会使用该LIST
命令并支持数十种不同的列表格式。
(我是WinSCP的作者)
我发现工作的唯一方法是依赖“WebRequestMethods.Ftp.DeleteFile”,如果文件夹或带有文件的文件夹会出现异常,所以我创建了一个新的内部方法来递归地删除目录这里是代码
public void delete(string deleteFile)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Resource Cleanup */
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) {
//Console.WriteLine(ex.ToString());
try
{
deleteDirectory(deleteFile);
}
catch { }
}
return;
}
和目录删除
/* Delete Directory*/
private void deleteDirectory(string directoryName)
{
try
{
//Check files inside
var direcotryChildren = directoryListSimple(directoryName);
if (direcotryChildren.Any() && (!string.IsNullOrWhiteSpace(direcotryChildren[0])))
{
foreach (var child in direcotryChildren)
{
delete(directoryName + "/" + child);
}
}
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + directoryName);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Resource Cleanup */
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}
列出目录孩子
/* List Directory Contents File/Folder Name Only */
public string[] directoryListSimple(string directory)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Establish Return Communication with the FTP Server */
ftpStream = ftpResponse.GetResponseStream();
/* Get the FTP Server's Response Stream */
StreamReader ftpReader = new StreamReader(ftpStream);
/* Store the Raw Response */
string directoryRaw = null;
/* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
/* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Return an Empty string Array if an Exception Occurs */
return new string[] { "" };
}
/* List Directory Contents in Detail (Name, Size, Created, etc.) */
public string[] directoryListDetailed(string directory)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Establish Return Communication with the FTP Server */
ftpStream = ftpResponse.GetResponseStream();
/* Get the FTP Server's Response Stream */
StreamReader ftpReader = new StreamReader(ftpStream);
/* Store the Raw Response */
string directoryRaw = null;
/* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
/* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Return an Empty string Array if an Exception Occurs */
return new string[] { "" };
}
FtpWebRequest 提供删除操作。这是一段代码来实现这一点:
FtpWebRequest reqFTP = FtpWebRequest.Create(uri);
// Credentials and login handling...
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
string result = string.Empty;
FtpWebResponse response = reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
它应该适用于文件和目录。确实,请检查您是否拥有正确的权限。
此外,当文件夹不为空时,您无法删除它们。您必须递归遍历它们才能删除内容。
由于正确的权限问题引发的异常并不总是很清楚......
很重要的一点
正如刚才提到的..
当文件夹不为空时,您无法删除它们。您必须递归遍历它们才能删除内容。
public void Deletedir(string remoteFolder)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/"+ remoteFolder);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;***strong text***
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Get the FTP Server's Response Stream */
ftpStream = ftpResponse.GetResponseStream();
/* Open a File Stream to Write the Downloaded File */
}
catch { }
}
这就是您可以使用的代码。这是您如何使用它的方法,例如,在单击按钮时。
private void button5_Click(object sender, EventArgs e)
{
ftp ftpClient = new ftp(@"SERVICE PROVIDER", "USERNAME", "PASSWORD");
ftpClient.Deletedir("DIRECTORY U WANT TO DELETE");
}
请记住,您的文件夹应该是空的。