I want to list all files from my ftp folder, I am using this code. But it gives me twice the name of files. What is wrong with it?
private void ListFilesOnServer()
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConfigurationSettings.AppSettings.Get("IncomingFtpPath"));
request.Credentials = new NetworkCredential("user", "password");
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (System.IO.Path.GetExtension(line) == ".xml")
{
WaitingListBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(line));
}
}
reader.Close();
response.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Use a debugger to see what is contain in "response"
Make sure that your function is called only once.
Also, are your sure that the "duplicates" are not files with the same name but different absolute paths ?
Few remarks on your code:
Prefer using directives when manipulating streams, instead of manually closing them : here your code might throw exceptions without releasing the resources.
Avoid swallowing exceptions (even if you display them)
private void ListFilesOnServer()
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConfigurationSettings.AppSettings.Get("IncomingFtpPath"));
request.Credentials = new NetworkCredential("user", "password");
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using(StreamReader reader = new StreamReader(response.GetResponseStream())
{
string line = null;
while((line = reader.ReadLine()) != null)
{
if (System.IO.Path.GetExtension(line) == ".xml")
{
WaitingListBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(line));
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
// throw e
}
Related
This is basically my first API handling with C#, so I read and tried to create so I can handle the JSON, but I ain't getting any response, tried to display it in a label text, but I am not getting any error nor any response.
It is supposed to show the JSON in a label with answer with basic auth, so then, I can handle it, because I have been able to see the JSON if I log via POSTMAN, but if I run the code, all I see is nothing, even tho it is wrapped in a string.
public partial class callUni : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strResponse = string.Empty;
strResponse = makeRequest();
answer.Text = strResponse;
}
public string makeRequest()
{
string strRequest = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"https://unicard-api.asf.edu.mx:8443/api/Acessos/Entradas");
request.Credentials = GetCredential();
request.PreAuthenticate = true;
request.Method = httpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("error code = " + response.StatusCode);
}
//Vamos a procesar el JSON que viene de UNICARD
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strRequest = reader.ReadToEnd();
}
}
}
}
}
catch (Exception e) { };
return strRequest;
}
private CredentialCache GetCredential()
{
string url = #"https://unicard-api.asf.edu.mx:8443/api/Acessos/Entradas";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["xxxxx"], ConfigurationManager.AppSettings["xxxx"]));
return credentialCache;
}
}
}
You say "I am not getting any error nor any response.", but I think you are getting an error, but your line here is hiding it from you:
catch (Exception e) { };
Try either logging or displaying e.ToString() inside the catch block then investigating from there.
As a sidenote, Microsoft explicitly says not to throw ApplicationException. Either find a more relevant Exception class to use or throw Exception. https://msdn.microsoft.com/en-us/library/system.applicationexception%28v=vs.110%29.aspx#Remarks
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'm using the below method to upload files from local server to FTP server, here i'm creating a new connection and initiating a new session each and every file uploading and closing the same. how to achieve this in single initiated session in c#.
this is my code
public bool UploadTempFilesToFTP()
{
string[] fileList;
try
{
ConfiguredValues conObj = new ConfiguredValues();
conObj.PickTheValuesFromConfigFile();
fileList = Directory.GetFiles(conObj.tempPath);
foreach (string FileName in fileList)
{
FtpWebRequest upldrequest = (FtpWebRequest)FtpWebRequest.Create(conObj.tempOutboundURL + FileName);
upldrequest.UseBinary = true;
upldrequest.KeepAlive = false;
upldrequest.Timeout = -1;
upldrequest.UsePassive = true;
upldrequest.Credentials = new NetworkCredential(conObj.user, conObj.pass);
upldrequest.Method = WebRequestMethods.Ftp.UploadFile;
string destinationAddress = conObj.tempPath;
FileStream fs = File.OpenRead(destinationAddress + FileName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream requestStr = upldrequest.GetRequestStream();
requestStr.Write(buffer, 0, buffer.Length);
requestStr.Close();
requestStr.Flush();
FtpWebResponse response = (FtpWebResponse)upldrequest.GetResponse();
response.Close();
File.Delete(destinationAddress + FileName);
}
Console.WriteLine("Uploaded Successfully to Temp folder");
return true;
}
catch (Exception ex)
{
Console.WriteLine("Upload failed. {0}", ex.Message);
return false;
}
}
it's weird that i answer an old question but i try almost everything to upload multiple files to ftp with no luck while the solution is very simple and effective, using LOOPING - foreach solved the issue for me i use the below function to Upload the files in one simple step..
public void Uploadbulkftpfiles(string[] list)
{
bool ife;// is folder exists
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftpsite.com/folder");
request.Credentials = new NetworkCredential("Username", "Password");
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
ife = true;
}
catch (Exception)
{
ife = false;
}
/////////////////////////////////////////////begin of upload process
if (ife)//the folder is already exists
{
foreach (var str in list)
{
try
{
FtpWebRequest requestUP2 = (FtpWebRequest)WebRequest.Create("ftp://ftpsite.com/folder" + str);
requestUP2.Credentials = new NetworkCredential("UserName", "Password");
requestUP2.Method = WebRequestMethods.Ftp.UploadFile;
requestUP2.KeepAlive = false;
requestUP2.UsePassive = true;
using (Stream fileStream = File.OpenRead("ftp://ftpsite.com/folder" + str))
using (Stream ftpStream = requestUP2.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
}
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
}
else if (!ife)
{
//CREATE THE FOLDER
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp:ftpsite/folder");
request.Credentials = new NetworkCredential("UserName", "Password");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (Exception excr) { MessageBox.Show(excr.Message); }
//UPLOAD THE FILES
foreach (var str in list)
{
try
{
FtpWebRequest requestUP2 = (FtpWebRequest)WebRequest.Create("ftp://ftpsite.com/folder" + str);
requestUP2.Credentials = new NetworkCredential("UserName", "Password");
requestUP2.Method = WebRequestMethods.Ftp.UploadFile;
requestUP2.KeepAlive = false;
requestUP2.UsePassive = true;
using (Stream fileStream = File.OpenRead("ftp://ftpsite.com/folder" + str))
using (Stream ftpStream = requestUP2.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
}
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
}
}
The ftp protocol is intended to works on request basis.
You start a request with a method (in your case UploadFile).
The only thing you can do is to KeepAlive your request to avoid connection closing
upldrequest.KeepAlive = true;
on every request you create except the last one. This will make a login only the first FTPWebRequest.
Then when you create the last FTPWebRequest, set
upldrequest.KeepAlive = false;
and it will close the connection when done.
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
I'm trying to create a method in C# to return a string of a web pages html content from the url. I have tried several different ways, but I am getting the error System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.
The following works fine locally, but gets the above error when running on a remote server:
public static string WebPageRead(string url)
{
string result = String.Empty;
WebResponse response = null;
StreamReader reader = null;
try
{
if (!String.IsNullOrEmpty(url))
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
}
catch (Exception exc)
{
throw exc;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
}
return result;
}
This is probably not the problem, but try the following:
public static string WebPageRead(string url)
{
if (String.IsNullOrEmpty(url))
{
return null;
}
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (request == null)
{
return null;
}
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader =
new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
I echo the earlier answer that suggests you try this with a known good URL. I'll add that you should try this with a known good HTTP 1.1 URL, commenting out the line that sets the version to 1.0. If that works, then it narrows things down considerably.
Thanks for the responses, the problem was due to a DNS issue on the remote server! Just to confirm, I went with the following code in the end:
public static string WebPageRead(string url)
{
string content = String.Empty;
if (!String.IsNullOrEmpty(url))
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (request != null)
{
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
content = reader.ReadToEnd();
}
}
}
}
catch (Exception exc)
{
throw exc;
}
}
}
return content;
}
Had a problem like this before that was solved by opening the url in IE on the machine with the problem. IE then asks you whether you want to add the url to the list of secure sites. Add it and it works for that url.
This is just one of the possible causes. Seriously a lot of other problems could cause this. Besides the problem described above, the best way I've found to solve this is the just catch the exception and retry the request.