2013-07-12 30 views
8

我的程序可以將文件上傳到使用該代碼的ftp服務器:現在我需要刪除一些文件,我不能這樣做,正確刪除從FTP文件在C#

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); 

回答

32

你需要用這個類來做那個,我想。

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(); 
1

當你需要刪除的文件,您應該使用的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

2
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; 
} 
9
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);