I have added the following code in my C#.net application in visual studio 2010
WebRequest request = WebRequest.Create("ftp://myftp.com");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("myusername", "12344");
using (var resp = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
But I am getting following error.
The requested URI is invalid for this FTP command.
Please suggest solution. Thanks
If you just want to check file information you should try changing the request.Method to WebRequestMethods.Ftp.ListDirectoryDetails instead:
WebRequest request = WebRequest.Create("ftp://myftp.com");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential("myusername", "12344");
using (var resp = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
Uri should be ftp:// + IP or ftpServerName + / Folder_to_create_Name
So, see follow code:
WebRequest request = WebRequest.Create("ftp://myftp.com/FOLDER_TO_CREATE/");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("myusername", "12344");
using (var resp = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
You must specify a sub-directory you wish to create; you can't create the root, which is what it appears you are trying to do. Hence the error.
Related
i am trying to send a POST request with body to WordPress API. I am still getting 401 error.
I decided to use: https://gist.github.com/DeskSupport/2951522 to authorize via OAuth 1.0 and it works perfectly with GET method. Then i wanted to implement another method which sends simple body.
That's my code:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = _consumerKey;
oauth["consumer_secret"] = _consumerSecret;
oauth["token"] = _accessToken;
oauth["token_secret"] = _tokenSecret;
var appUrl = _baseUrl + url;
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
string body = GenerateBody(parameters);
byte[] encodedData = Encoding.ASCII.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
request.ContentLength = encodedData.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream newStream = request.GetRequestStream();
newStream.Write(encodedData, 0, encodedData.Length);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
}
}
The result of method GenerateBody is user_login=login&user_pass=BXE&04K44DoR1*a
I also tried to change the '&' character to '%26' but it didn't work.
This request works via Postman and i don;t know what's wrong.
OK, I found a solution.
https://blog.dantup.com/2016/07/simplest-csharp-code-to-post-a-tweet-using-oauth/
This guy wrote the way to make this request. What is also important you have to change a oauth_nonce for unique token.
I have tried every variation of the below I can think of.
client.Credentials = new NetworkCredential(ftpInfo.ftpUserName, ftpInfo.ftpPassWord);
client.BaseAddress = "ftp://99.999.9.99";
var response = client.UploadFile("testFile.txt", "C:\\ftproot\\testfile\\012\\Drop\\testFile.txt");
I know the username and password are correct.
If I connect to the server using filezilla from the same box it works.
I have tried not haivng ftp:// on it -- I have to be missing something very simple.
Here is the error:
{"Unable to connect to the remote server"}
Response {System.Net.FtpWebResponse} System.Net.WebResponse {System.Net.FtpWebResponse}
ContentType '($exception).Response.ContentType' threw an exception of type 'System.NotImplementedException' string {System.NotImplementedException}
UPDATE:
I don't know what is wrong with the question. I have given as much info as I have on it.
Here is a current test using some of the suggestions in the notes.
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("password", "loginname");
client.UploadFile("ftp://99.999.6.130/testFile.txt", "STOR", "c:\\testfile.txt");
}
That just states that I am not logged in.
The below is working....I will close the question out when it lets me.
Finale Update -- working solution:
public static bool UploadFile(string url, string userName, string password, string file, out string statusDescription)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(userName, password);
// Copy the entire contents of the file to the request stream.
var sourceStream = new StreamReader(file);
var fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
var getResponse = request.GetResponse();
Console.WriteLine($"{fileContents.Length} {getResponse} ");
}
}
The below is a working solution.
public static bool UploadFile(string url, string userName, string password, string file, out string statusDescription)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(userName, password);
// Copy the entire contents of the file to the request stream.
var sourceStream = new StreamReader(file);
var fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
var getResponse = request.GetResponse();
Console.WriteLine($"{fileContents.Length} {getResponse} ");
}
}
https://api.github.com/users/[UserName] can be accessed via browser. I get a Json result. But I want to retrieve the same information programmatically.
I'm using the below code, which is not working as expected. Please advice.
var credentials =
string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:",
githubToken);
credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic", credentials);
var contents =
client.GetStreamAsync("https://api.github.com/users/[userName]").Result;
As a result of the above code, I'm getting "Aggregate Exception".
How to achieve the requirement using c# code??? Please help
Note: Not expecting a solution with Octokit. Need proper c# code.
I found the solution. Here is the code.
HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.UserAgent = "Anything";
webRequest.ServicePoint.Expect100Continue = false;
try
{
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
string reader = responseReader.ReadToEnd();
var jsonobj = JsonConvert.DeserializeObject(reader)
}
}
catch
{
return;
}
}
I have a web service URL which has username and password authentication mode. I have to first pass the username and password, and if I am authenticated, I can upload a text or XML file onto the server. I am looking for a C# code to do the same process, but I'm unable to find it.
Any suggestions would be highly appreciated.
I am using following code-
if (!string.IsNullOrEmpty(txtfile))
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.KeepAlive = false;
request.SendChunked = true;
request.AllowAutoRedirect = true;
request.Method = "Post";
request.ContentType = "text/xml";
request.Credentials = new NetworkCredential(userName, password);
var encoder = new UTF8Encoding();
var data = encoder.GetBytes(txtfile);
request.ContentLength = data.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
WebResponse response = null;
response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
}
You might want to try using the WebClient Class. There is a simple example about the WebClient.UploadFile Method which could fit your scenario.
I am making a Get request with following code:
TheRequest = (HttpWebRequest)WebRequest.Create(aURL);
TheRequest.Method = "GET";
TheRequest.CookieContainer = TheCookies;
TheRequest.UserAgent = GetUserAgent();
TheRequest.KeepAlive = false;
TheRequest.Timeout = 20000;
TheRequest.ReadWriteTimeout = 20000;
TheRequest.AllowAutoRedirect = true;
TheRequest.Headers.Add("Accept-Language", "en-us");
TheResponse = (HttpWebResponse)TheRequest.GetResponse();
TheResponseString = new StreamReader(TheResponse.GetResponseStream(), Encoding.ASCII).ReadToEnd();
After this I take the cookies as follows:
string theCookieHeader = TheResponse.Headers[HttpResponseHeader.SetCookie];
Then I process the string to be in proper cookie format and put it in cookie container to give it in next POST request. From the Response string (TheResponseString) I create the proper Post data and the cookies from cookiecontainer.
My code for POST request is as follows:
TheRequest = (HttpWebRequest)WebRequest.Create(aURL);
TheRequest.Method = "POST";
TheRequest.CookieContainer = TheCookies;
TheRequest.UserAgent = GetUserAgent();
TheRequest.KeepAlive = false;
TheRequest.Timeout = 20000;
TheRequest.ReadWriteTimeout = 20000;
TheRequest.AllowAutoRedirect = true;
TheRequest.ContentType = "application/x-www-form-urlencoded";
TheRequest.Headers.Add("Accept-Language", "en-us");
byte[] bytes = Encoding.ASCII.GetBytes(aPostDataString);
TheRequest.ContentLength = bytes.Length;
Stream oStreamOut = TheRequest.GetRequestStream();
oStreamOut.Write(bytes,0,bytes.Length);
oStreamOut.Close();
TheResponse = (HttpWebResponse)TheRequest.GetResponse();
TheResponseString = new StreamReader(TheResponse.GetResponseStream(), Encoding.ASCII).ReadToEnd();
Now the problem is I have two websites,they are partner websites,they have every thing same(It seems but if you doubt about anything then please tell me),but for one website it works fine and for other one it gives the response string of websites Error Page.
Please help me what to see for diagnosing the problem.
I had similar problem. Try to save the cookies from request, after you got the responce or even better, put this code in finally block. Run it once for TheRequest.Host and second time for the host of your second site. Also look if you need http or https
foreach (Cookie c in TheRequest.CookieContainer.GetCookies(new Uri("http://" + TheRequest.Host)))
{
TheCookies.SetCookies(new Uri("http://" + TheRequest.Host), c.Name + "=" + c.Value);
}