我想删除FTP中的文件夹。
FTPClient object可以删除它吗?
发布于 2011-01-26 03:40:40
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();它应该可以在文件和目录上工作。确实,请检查您是否拥有正确的权限。
此外,您不能在文件夹不为空时将其删除。您必须递归地遍历它们以删除之前的内容。
由于权限问题而抛出的异常并不总是非常清楚...
发布于 2016-09-09 21:29:57
要删除空目录,请使用FtpWebRequest的RemoveDirectory“方法”
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);不过,如果你需要删除一个非空的目录,它会变得更加复杂。在FTP类(或.NET框架中的任何其他FtpWebRequest实现)中不支持递归操作。您必须自己实现递归:
列出remote directory
棘手的部分是从子目录中识别文件。在FtpWebRequest中,无法以可移植的方式做到这一点。遗憾的是,FTP不支持MLSD命令,该命令是在FtpWebRequest协议中检索带有文件属性的目录列表的唯一可移植方法。另请参见Checking if object on FTP server is file or directory。
您可以选择:
LIST ListDirectoryDetails方法),并尝试解析特定于服务器的列表。许多FTP服务器使用*nix样式的列表,在这种列表中,您通过条目开头的d来标识目录。但许多服务器使用不同的格式。下面的示例使用这种方法(假设格式为*nix )。static void DeleteFtpDirectory(string url, NetworkCredential credentials)
{
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
List<string> lines = new List<string>();
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader 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
{
FtpWebRequest deleteRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
deleteRequest.Credentials = credentials;
deleteRequest.GetResponse();
}
}
FtpWebRequest removeRequest = (FtpWebRequest)WebRequest.Create(url);
removeRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
removeRequest.Credentials = credentials;
removeRequest.GetResponse();
}使用它的方式与前一个(平面)实现相同。
虽然Microsoft does not recommend FtpWebRequest for a new development。
或者使用支持递归操作的第三方库。
例如,使用WinSCP .NET assembly,只需调用一次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();
} 如果服务器支持,WinSCP会在内部使用MLSD命令。如果没有,它将使用LIST命令并支持数十种不同的列表格式。
(我是WinSCP的作者)
发布于 2014-03-25 09:07:30
我发现唯一有效的方法是依靠"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[] { "" };
}https://stackoverflow.com/questions/4797508
复制相似问题