18

我的程序可以使用以下代码将文件上传到 FTP 服务器:

WebClient client = new WebClient();
client.Credentials = new System.Net.NetworkCredential(ftpUsername, ftpPassword);
client.BaseAddress = ftpServer;
client.UploadFile(fileToUpload, WebRequestMethods.Ftp.UploadFile, fileName);

现在我需要删除一些文件,但我做不到。我应该用什么代替

client.UploadFile(fileToUpload, WebRequestMethods.Ftp.UploadFile, fileName);
4

4 回答 4

50

我认为,您需要使用FtpWebRequest类来执行此操作。

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);

//If you need to use network credentials
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); 
//additionally, if you want to use the current user's network credentials, just use:
//System.Net.CredentialCache.DefaultNetworkCredentials

request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Delete status: {0}", response.StatusDescription);  
response.Close();
于 2013-07-12T14:27:17.307 回答
16
public static bool DeleteFileOnFtpServer(Uri serverUri, string ftpUsername, string ftpPassword)
{
    try
    {
        // The serverUri parameter should use the ftp:// scheme.
        // It contains the name of the server file that is to be deleted.
        // Example: ftp://contoso.com/someFile.txt.
        // 

        if (serverUri.Scheme != Uri.UriSchemeFtp)
        {
            return false;
        }
        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
        request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
        request.Method = WebRequestMethods.Ftp.DeleteFile;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        //Console.WriteLine("Delete status: {0}", response.StatusDescription);
        response.Close();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }            
}

用法:

DeleteFileOnFtpServer(new Uri (toDelFname), user,pass);
于 2015-02-23T23:26:28.353 回答
3
public static bool DeleteFileOnServer(Uri serverUri)
{

if (serverUri.Scheme != Uri.UriSchemeFtp)
{
    return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Delete status: {0}",response.StatusDescription);  
response.Close();
return true;
}
于 2015-02-19T13:00:29.833 回答
2

当您需要删除文件时,您应该使用 FtpWebRequest:

// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Delete status: {0}",response.StatusDescription);  
response.Close();

参考:http: //msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx

于 2013-07-12T14:30:40.697 回答