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;
}
Related
I have a few .log files on an FTP server. I need to download them on my drive. Alternatively, read and display contents. I've read related posts here, and came up with the code:
DOWNLOAD
public void DownloadFile(String infile)
{
String myUrl = String.Format("ftp://{0}/{1}", IpAddress, infile);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(myUrl));
request.Credentials = new NetworkCredential(UserName, Password);
request.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
String output = String.Format("{0}", infile);
using (StreamWriter destination = new StreamWriter(output))
{
destination.Write(reader.ReadToEnd());
destination.Flush();
}
reader.Close();
response.Close();
}
READ
public string ReadTxtFile2(String infile)
{
WebClient request = new WebClient();
String url = String.Format("ftp://{0}/{1}", IpAddress, infile);
request.Credentials = new NetworkCredential(UserName, Password);
try
{
// also tried: String fileString = request.DownloadString(url);
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
return fileString;
}
catch (WebException e)
{
return e.Message;
}
}
Somehow the download returns me an empty 0 kb file and a read() function outputs an empty contents. I can't find out why, any help?
NOTE: files do exist on server, I can list them.
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();
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 have code what gets a content of some FTP directory. At some servers I've tested it works fine.
But at one server this method throws an exception when we try to get response.
public static List<string> ListDirectory(string dirPath, string ftpUser, string ftpPassword)
{
List<string> res = new List<string>();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dirPath);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
res.Add(reader.ReadLine());
}
reader.Close();
response.Close();
return res;
}
At catch section I have something like this
catch (WebException e)
{
FtpWebResponse response = (FtpWebResponse)e.Response;
/*in my case response.Status = ActionNotTakenFileUnavailableOrBusy*/
....
}
It works before but now it fails when folder is empty. If there is something there it works. And I can see this directory with TotalCommander.
Any ideas why?
This is an example on how to get a listing of a remote directory using the free library System.Net.FtpClient available from CodePlex.
I have used it in many occasions and, in my opinion, is more easy to work with
public void GetListing()
{
using (FtpClient conn = new FtpClient())
{
conn.Host = "your_ftp_site_url";
conn.Credentials = new NetworkCredential("your_user_account", "your_user_password");
foreach (FtpListItem item in conn.GetListing(conn.GetWorkingDirectory(), FtpListOption.Modify | FtpListOption.Size))
{
switch (item.Type)
{
case FtpFileSystemObjectType.Directory:
Console.WriteLine("Folder:" + item.Name);
break;
case FtpFileSystemObjectType.File:
Console.WriteLine("File:" + item.Name);
break;
}
}
}
}
You can find the download from this pages
Can anyone please tell me from where would i get the time of uploaded file at the FTP server?
class listFiles
{
public static void Main(string[] args)
{
listFiles l = new listFiles();
l.getFileList(ftpConnection,"test123","pass123"); //ftp url
}
private void getFileList(string FTPAddress, string username, string password)
{
List<string> files = new List<string>();
try
{
//Create FTP request
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
//Application.DoEvents();
// string fileType = reader.ReadLine();
files.Add(reader.ReadLine());
}
//Clean-up
reader.Close();
responseStream.Close(); //redundant
response.Close();
}
catch (Exception)
{
Console.WriteLine("There was an error connecting to the FTP Server");
}
//If the list was successfully received, display it to the user
//through a dialog
if (files.Count != 0)
{
foreach (string file in files)
{
Console.WriteLine(file);
}
}
}
try with FtpWebResponse.LastModified Property
using (FtpWebResponse resp = (FtpWebResponse)request.GetResponse())
{
var lastModified = resp.LastModified ;
}
you need to get responses for each file, in your current code you have already a list of files, by using that file name build full path to ftp file you need to find the create date. after that create ftp request to that full ftp file path. then you can read the last modified date of response object.