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();
Related
This question already has an answer here:
C# Download all files and subdirectories through FTP
(1 answer)
Closed 5 years ago.
I want to fetch the files from folder through FTP using c#, I have folder name called MyFolder, inside of this folder i have multiple folder, i need to fetch each file from all this folders which is inside the my MyFolder.Below code which i am getting all directories,Now i need to get each file.
Eg:httpdocs/Myfolder/newfolder/newfile.txt
/newfile1.txt
/newfile2.txt
httpdocs/Myfolder/newfolder1/newfile.txt
httpdocs/Myfolder/newfolder2/newfile.txt
FtpWebRequest ftpRequest =(FtpWebRequest)WebRequest.Create("ftp://www.xxxxxxx.com/httpdocs/MyFolder");
ftpRequest.Credentials = new NetworkCredential("xxxxx", "xxxxxx");
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();
}
Have you had a look at the MSDN Documentation?
https://msdn.microsoft.com/de-de/library/ms229711(v=vs.110).aspx
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
Edit: Already on StackOverflow Have a look here.
This method does work and does adding the files to the listBox.
But some of the files are directories and i wonder if there is a way to display the directories witha directory symbol this yellow directory near it ?
public void getFtpFileList()
{
List<string> files = new List<string>();
try
{
FtpWebRequest request = FtpWebRequest.Create("ftp://"+ txtHost.Text) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(txtUsername.Text, txtPassword.Text);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
files.Add(reader.ReadLine());
}
foreach (string file in files)
{
listBox1.Items.Add(file);
}
reader.Close();
responseStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
This is a screenshot on the top left is my program and under it it's my ftp.
I want somehow to display on the listBox as much as close the way it look like in my ftp server.
I receive a file on the FTP server, the name of the file is generated dynamically. I am trying to write a program to check if any file exists on the server.
string userName = Dts.Variables["User::SFTPUsername"].Value.ToString();
string password = Dts.Variables["User::SFTPPassword"].Value.ToString();
**string fileName = Dts.Variables["User::FilePattern"].Value.ToString();**
string ftpURL = String.Format("ftp://11.11.11/upload/{0}", fileName);
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(userName, password);
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpURL);
ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
ftpRequest.Credentials = new NetworkCredential(userName, password);
using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
{
byte[] newFileData = request.DownloadData(ftpURL.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
string strexist = String.Format("exist");
MessageBox.Show(strexist);
Dts.Variables["User::FileExists"].Value = true;
}
This works well only when I specify the "fileName". Is there anyway I can do a wildcard search ("*.txt") or search if anyfile is in the upload folder?
Any help appreciated!!
You can list out the file names from the FTP. Like Below...
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL);
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
using (Stream respStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
//Read each file name from the response
for (string fname = reader.ReadLine(); fname != null; fname = reader.ReadLine())
{
// Add the file name into a list
}
}
If the list count is 0 then there is no file available. Also you will get the each file name in a list from the single request.
Iterate the list values using foreach loop. And make the above code as a method. Pass the File name to the method.
You can also do make sure particular file name is exists or not in the list.
Note: In the above code no need to provide the file name to the Url.
There sure is!
Try setting ftpURL to the directory name in question and request.Method to WebRequestMethods.Ftp.ListDirectory;.
var request = (FtpWebRequest)WebRequest.Create("ftp://www.example.com/uploads");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(userName, password);
using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
{
...
}
For examples, check out http://timtrott.co.uk/ultimate-guide-ftp/ and http://msdn.microsoft.com/en-us/library/ms229716%28v=vs.110%29.aspx (note: the latter uses WebRequestMethods.Ftp.ListDirectoryDetails instead of ListDirectory, so you may need to slightly modify it).
I need some help with some code that is not working for some reason. I'm making a method that gets a list of files in a FTP directory. Every time I debug the app, a WebException is thrown with the StatusCode of 530 (not logged in). Keep in mind that I am 100% positive the address, username, and password are correct. Here's the method:
public static List<string> GetFileList(string Directory)
{
List<string> Files = new List<string>();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ServerInfo.Root + Directory));
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(ServerInfo.Username, ServerInfo.Username);
FtpWebResponse response = (FtpWebResponse)request.GetResponse(); //Error occurs here
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string CurrentLine = reader.ReadLine();
while (!string.IsNullOrEmpty(CurrentLine))
{
Files.Add(CurrentLine);
CurrentLine = reader.ReadLine();
}
reader.Close();
response.Close();
return Files;
}
This is the value of ServerInfo.Root: "ftp://192.xxx.4.xx:21/MPDS" (partially censored for privacy)
I have used MessageBoxes to ensure the complete URI is correct, and it is.
I've been struggling with this problem for a long time now, so I hope you can help me fix it.
Thanks in advance!
You can try this code with some corrections:
public static List<string> GetFileList(string Directory)
{
List<string> Files = new List<string>();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ServerInfo.Root + Directory));
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(ServerInfo.Username, ServerInfo.Username); // Is this correct?
// request.Credentials = new NetworkCredential(ServerInfo.Username, ServerInfo.Password); // Or may be this one?
request.UseBinary = false;
request.UsePassive = true;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string CurrentLine = reader.ReadLine();
while (!string.IsNullOrEmpty(CurrentLine))
{
Files.Add(CurrentLine);
CurrentLine = reader.ReadLine();
}
reader.Close();
response.Close();
return Files;
}
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;
}