Could you please let me know how can i fetch the file names from a web directory at a service level. I have a wrapper services. Inside it I am trying to fetch file names. I couldn't find a solution.
If I understand the question correctly, which I may not since you werent too specific, sounds as easy as getting FTP listing:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
// 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("Directory List Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
}
}
Related
i can past this url into my browser and get the server time, https://api.binance.je/api/v3/time
But i am unable to get a response using below code. How can i debug this
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Create a request for the URL.
WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
I see that you are able to retrieve the json data from the website. Tested this on my side.
However if you are trying to get the value only you need to read the json string (responsefromServer). This can be done by using a nuget pakage called Newtonsoft.
Then you will have to add the following to your code.
Above namespace:
using Newtonsoft.Json.Linq;
In main function before closing reader enz:
//Create jsonObject object from the api call response
JObject jObject = JObject.Parse(responseFromServer);
//Read propertie called serverTime and convert this to string to match variabele set
string time = jObject["serverTime"].ToString();
//Write the given time
Console.WriteLine(time);
Your code will look like the following:
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// Create a request for the URL.
WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
//Create jsonObject object from the api call response
JObject jObject = JObject.Parse(responseFromServer);
//Read propertie called serverTime and convert this to string to match variabele set
string time = jObject["serverTime"].ToString();
//Write the given time
Console.WriteLine(time);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
The problem was down to my vpn. Even though i didnt have an active connection. I killed the background service and restarted it and is now working
Similar issue
httpclient-getasync-times-out-when-connected-to-vpn
This is the path I am trying to upload to the ftp server:
_ftp://ftp-server/products/productxx/versionxx/releasexx/delivery/data.zip
The problem is that the folders "productxx/versionxx/releasexx/delivery/" do not exist on the server.
Can I create them automatically while uploading the .zip file in c#
My coding at the moment is:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create(pathToFtp);
// Method set to UploadFile
request.Method = WebRequestMethods.Ftp.UploadFile;
// set password and username
request.Credentials = new NetworkCredential(UserName, Password);
// write MemoryStream in ftpStream
using (Stream ftpStream = request.GetRequestStream())
{
memoryStream.CopyTo(ftpStream);
}
I am getting the System.Net.WebException: "Can't connect to FTP: (553) File name not allowed" at "using (Stream ftpStream =request.GetRequestStream())"
but if my pathToFtp is _ftp://ftp-server/products/data.zip it´s working well
One of the request methods available is WebRequestMethods.Ftp.MakeDirectory. You should be able to use that to do what you want.
Something like this (though I've not tested it), should do the trick:
async Task CreateDirectory(string path)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
using (var response = (FtpWebResponse)(await request.GetResponseAsync()))
{
Console.WriteLine($"Created: {path}");
}
}
It's answered in more detail here How do I create a directory on ftp server using C#?
This question already has answers here:
How to check if an FTP directory exists
(11 answers)
Closed 4 years ago.
I am using FTP to upload files to a folder on an FTP server folder, but first I need to determine that the folder exists. MSDN contains an example of how to use FtpWebResponse to check if a folder exists:
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
// 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("Directory List Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
}
Using the code above, one can obtain a list of folders off the root level of the server, and I can do this in my own situation. That is NOT my question.
My question is, what if the folder I am wanting to write to is a SUBFOLDER of one of the folders that results from the call to ListDirectoryDetails? How do I dig deeper into the folder structure?
You can try this:
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://address/subfolder/subfolder");
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
// Directory exists, you can work on it.
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
// Directory not found.
}
}
}
This way, you are basically checking if you can list the directory by calling Ftp.ListDirectory as an FTP request method. If it fails, then your directory does not exist.
Let's say you want to use the subfolder temp. Then you have to append the folder to your URI like this:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/temp/somefile.xyz");
In this way you can access subfolders, subsubfolders and so on.
This is the code i'm using to upload a simple text file to my ipage.com ftp:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace ScrollLabelTest
{
class FtpFileUploader
{
static string ftpurl = "ftp://ftp.newsxpressmedia.com";
static string filename = #"c:\temp\test.txt";
static string ftpusername = "newsxpressmediacom";
static string ftppassword = "*****";
static string value;
public static void test()
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpurl + "/" + Path.GetFileName(filename));
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(ftpusername, ftppassword);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#"c:\temp\test.txt");
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();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
catch(Exception err)
{
string t = err.ToString();
}
}
}
}
I see the text file: test.txt on my ipage ftp now. But how can i display on my weebly site the content of the text file i just uploaded ? The ftp in ipage.com is my website domain name ftp account.
I just talked to the help support live chat they told me there is no way to do it.
What i want to do is to upload somehow a text file from my hard drive to my site and display the content of the text file on my site each a minute since the text file is getting update every a minute.
This is what they wrote about the ipage ftp:
You can build your site using Web authoring tools, and then use an FTP program to upload the Web pages to your iPage account.
To access your account using an FTP client, you need to connect to ftp.newsxpressmedia.com with your FTP username and password.
And: newsxpressmedia.com is my website domain on weebly.
I can edit drag and drop and design my site on weebly but how can i display the content of a text file every a minute ?
I know not all but some ftp sites have a "change permissions" setting for each file or folder, if it has that setting then you can change permissions to allow anybody to view the file and just put the direct file location
I'm trying to understand the MSDN documentation for FtpWebRequest and more specificaly, how to upload using FTP and C#
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
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.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
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();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
}
}
}
In the code above they reference 2 file types. Am I right in assuming that testfile.txt is the 'source' file (on the local computer) and test.htm is what testfile.txt will be renamed too?
Yes - you're uploading to test.htm, loading the data from testfile.txt. You can tell that because test.htm is part of the URL (so is remote) whereas testfile.txt is loaded by just creating a StreamReader over a file.
(It's worth noting that this code is pretty bad in various ways, by the way - particularly around resource disposal. Don't treat it as embodying best practices...)