My program can upload files into an FTP server using this code:
WebClient client = new WebClient();
client.Credentials = new System.Net.NetworkCredential(ftpUsername, ftpPassword);
client.BaseAddress = ftpServer;
client.UploadFile(fileToUpload, WebRequestMethods.Ftp.UploadFile, fileName);
Right now I need to delete some files and I can't do that right. What should I use instead of
client.UploadFile(fileToUpload, WebRequestMethods.Ftp.UploadFile, fileName);
You'll need to use the FtpWebRequest class to do that one, I think.
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();
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;
}
}
Usage:
DeleteFileOnFtpServer(new Uri (toDelFname), user,pass);
You should use FtpWebRequest when you need to delete files:
// 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();
ref:
http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx
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;
}
Related
I am trying to create a directory on my FTP server. I had already created ContractorDoc directory on server and want to create new directory NewDirectory in it.
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://abc.xyz.com/ContractorDoc/NewDirectory");
// Step 2 - Configure the connection request
request.Credentials = new NetworkCredential("uname", "passsword");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
// Step 3 - Call GetResponse() method to actually attempt to create the directory
FtpWebResponse makeDirectoryResponse = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
String status = ((FtpWebResponse)ex.Response).StatusDescription;
}
I get an exception:
550 Cannot create a file when that file already exists.
Am I missing something?
I think he's got to make sure there folder.
There is no error in the code. Maybe there's a problem with the server.
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://abc.xyz.com/ContractorDoc");
ftpRequest.Credentials =new NetworkCredential("uname","password");
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
List<string> directories = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
directories.Add(line);
line = streamReader.ReadLine();
}
streamReader.Close();
I'm having issue uploading file to ftp site over SSL to specific directory. I'm using System.Net.FtpWebRequest class for this purpose. Upload going through fine. But the file always dropped to home directory. Any idea what might be doing wrong? Appreciate your help.
public bool UploadFile(string srcFilePath, string destFilePath = null)
{
if (String.IsNullOrWhiteSpace(srcFilePath))
throw new ArgumentNullException("Source FilePath.");
if (String.IsNullOrWhiteSpace(destFilePath))
destFilePath = Path.GetFileName(srcFilePath);
Uri serverUri = GetUri(destFilePath);
//// the serverUri should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
return false;
// get the object used to communicate with the server.
FtpWebRequest request = CreateFtpRequest(serverUri, WebRequestMethods.Ftp.UploadFile);
// read file into byte array
StreamReader sourceStream = new StreamReader(srcFilePath);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
// send bytes to server
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Debug.WriteLine("Response status: {0} - {1}", response.StatusCode, response.StatusDescription);
return true;
}
private FtpWebRequest CreateFtpRequest(Uri serverUri, string method)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.EnableSsl = true;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
request.Credentials = new NetworkCredential(_userName, _password);
request.Method = method;
return request;
}
private Uri GetUri(string remoteFilePath)
{
return new Uri(_baseUri, remoteFilePath);
}
OK. Finally figured it out. It is .NET 4.0 framework issue. Build the solution with .NET 3.5, it worked beautifully.
Hate to see bugs in new releases of .NET from Microsoft and wasting lot of quality time in figuring out.
I found a number of similar articles here but did not manage to solve my problem still.
I am trying to upload a text file to an ftp server. I used a number of methods and all of them i get same error : "Can not connect to remote server"
Method1 :
filename is the full path where the file is located
private string Upload(string ftpServer, string userName, string password, string filename)
{
string reply = "Success";
try
{
using (System.Net.WebClient client = new System.Net.WebClient()) //System.Net.WebClient client = new System.Net.WebClient()
{
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Proxy = new WebProxy();
FileInfo fi = new FileInfo(filename);
client.UploadFile(ftpServer + "//" + fi.Name, "STOR", filename);
}
}
catch (Exception ex)
{
reply = ex.Message;
}
return reply;
}
Method2:
filename = "D:\folder\file.txt"
public static void uploadFileUsingFTP(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + serverIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Proxy = null;
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(user, pass);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
FileStream fs = File.OpenRead(filename);
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = Convert.ToInt32(fs.Length);
byte[] buff = new byte[buffLength];
int contentLen;
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
string s = ex.Message;
}
}
Method3:
public static void Sample(string filename)
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://serverip/"); //test.htm
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential (user,passs);
try
{
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(filename);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
request.Proxy = null;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
Using each of them results in the same problem and yes i am able to connect to the ftp by using filezilla and also transfer files.
I know that i must be missing something very stupid but it is taking me so much time.
Any suggestion will be appreaciated.
Connection problems can be a nuisance to sort out. A tool like WireShark can be a big help in tracking down problems, e.g. when trying active vs. passive mode FTP transfers.
I've been using the following code with good results:
bool result = false;
long length = 0;
// Set up the FTP upload.
// The URI for the request specifies the protocol, the server and the filename.
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerUrl + "/" + targetFilename);
ftpRequest.EnableSsl = false;
ftpRequest.KeepAlive = true;
ftpRequest.ReadWriteTimeout = ftpTimeout; // To perform an individual read or write.
ftpRequest.Timeout = ftpTimeout; // To establish a connection or start an operation.
ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
// Upload the file.
using (FileStream fileStream = File.OpenRead(filename))
{
using (Stream ftpStream = ftpRequest.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
length = fileStream.Length;
ftpStream.Close();
}
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
if (ftpResponse.StatusCode == FtpStatusCode.ClosingData)
result = true;
else
throw new Exception(ftpResponse.StatusDescription + " (" + ftpResponse.StatusCode + ")");
ftpResponse.Close();
}
Have already replied in another thread, however repeating here as well. I faced the same issue, here was my solution.
request.Credentials = new NetworkCredential(
usernameVariable.Normalize(),passwordVariable.Normalize(),domainVariable.Normalize());
Details can be found here
Hope it helps someone.
Add the following in your web.config to have your FtpWebRequest use the default proxy
<defaultProxy enabled="true" useDefaultCredentials="true">
</defaultProxy>
I'm creating a simple drag-file-and-upload-automatically-to-ftp windows application
and I'm using the MSDN code to upload the file to the FTP.
The code is pretty straight forward:
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("{0}{1}", FTP_PATH, filenameToUpload));
request.Method = WebRequestMethods.Ftp.UploadFile;
// Options
request.UseBinary = true;
request.UsePassive = false;
// FTP Credentials
request.Credentials = new NetworkCredential(FTP_USR, FTP_PWD);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(fileToUpload.FullName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
writeOutput("Upload File Complete!");
writeOutput("Status: " + response.StatusDescription);
response.Close();
and it does get uploaded to the FTP
Problem is when I see the file on a browser, or simply download and try to see it on desktop I get:
I already used request.UseBinary = false; and request.UsePassive = false; but it does not seam to do any kind of good whatsoever.
What I have found out was that, the original file has 122Kb lenght and in the FTP (and after downloading), it has 219Kb...
What am I doing wrong?
By the way, the uploadFileToFTP() method is running inside a BackgroundWorker, but I don't really thing that makes any difference...
You shouldn't use a StreamReader but only a Stream to read binary files.
Streamreader is designed to read text files only.
Try with this :
private static void up(string sourceFile, string targetFile)
{
try
{
string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
////string ftpURI = "";
string filename = "ftp://" + ftpServerIP + "//" + targetFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
byte[] b = File.ReadAllBytes(sourceFile);
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
MessageBox.Show(ftpResp.StatusDescription);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The problems are caused by your code decoding the binary data to character data and back to binary data. Don't do this.
Use the UploadFile Method of the WebClient Class:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FTP_USR, FTP_PWD);
client.UploadFile(FTP_PATH + filenameToUpload, filenameToUpload);
}
Is there a simple, fast way to check that a FTP connection (includes host, port, username and password) is valid and working? I'm using C#. Thank you.
try something like this:
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create("ftp://ftp.google.com");
requestDir.Credentials = new NetworkCredential("username", "password");
try
{
WebResponse response = requestDir.GetResponse();
//set your flag
}
catch
{
}
this is the method I use, let me know if you know a better one.
/*Hola
Este es el metodo que utilizo si conoces uno mejor hasmelo saber
Ubirajara 100% Mexicano
isc.erthal#gmail.com
*/
private bool isValidConnection(string url, string user, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(user, password);
request.GetResponse();
}
catch(WebException ex)
{
return false;
}
return true;
}
This might be useful.
public async Task<bool> ConnectAsync(string host, string user, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host);
request.Credentials = new NetworkCredential(user, password);
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false; // useful when only to check the connection.
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse) await request.GetResponseAsync();
return true;
}
catch (Exception)
{
return false;
}
}
Use either System.Net.FtpWebRequest or System.Net.WebRequestMethods.Ftp to test your connection using your login credentials. If the FTP request fails for whatever reason the appropriate error message will be returned indicating what the problem was (authentication, unable to connect, etc...)
You could try using
System.Net.FtpWebRequest and then just check the GetResponseStream method.
So something like
System.Net.FtpWebRequest myFTP = new System.Net.FtpWebRequest
//Add your credentials and ports
try
{
myFTP.GetResponseStream();
//set some flags
}
catch ex
{
//handle it when it is not working
}
This is from the msdn site to diplay files from a server
public static bool DisplayFileFromServer(Uri serverUri)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
try
{
byte [] newFileData = request.DownloadData (serverUri.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
return true;
}