Creating directory on server using HttpWebRequest - c#

I am trying to create directory on server via https. But while returning the response it generates exceptions: “The remote server returned an error: (404) Not Found.”
The code is as follows:
string szURL3 = #"https://directoryurl/TestDir/";
//Create an HTTP request for the URL.
HttpWebRequest httpMkColRequest = (HttpWebRequest)WebRequest.Create(szURL3);
// Set up new credentials.
httpMkColRequest.Credentials = new NetworkCredential(_httpsUserName, _httpsPassword);
// Pre-authenticate the request.
httpMkColRequest.PreAuthenticate = true;
// Define the HTTP method.
httpMkColRequest.Method = #"MKCOL";
// Retrieve the response.
HttpWebResponse httpMkColResponse = (HttpWebResponse)httpMkColRequest.GetResponse();
//Write the response status to the console.
Console.WriteLine(#"MKCOL Response: {0}",httpMkColResponse.StatusDescription);
Could anybody support regarding this. I am able to get the directory information correctly in the same way. As I referred some links:
http://blogs.msdn.com/b/robert_mcmurray/archive/2011/10/18/sending-webdav-requests-in-net-revisited.aspx
According to this, what I understood is that the resources are locked. But how to unlock the resources for creating directory.
Please correct where modification required.

I solved the issue. The webDAV Configuration on the server was not enabled.

Related

ConvertApi doesn't follow HTTP 302 Redirect

I'm trying to convert a file which is located on a remote server.
I use ConvertApi for .NET.
My code:
string url = "http://test.com/myfile";
var convertApi = new ConvertApi("secret");
var response = await convertApi.ConvertAsync("web", "pdf", new ConvertApiParam("url", url));
This code fails (ConvertApi returns HTTP 500 Internal Server Error) because the remote server returns HTTP 302 Redirect with the exact file location.
But ConvertApi doesn't follow this redirect for some reason.
HTTP 302 Redirect is a very common way for file storage services to handle such downloads.
Is it a bug? Am I missing something? Maybe there is a special setting that forces ConvertApi to follow redirects?
The correct usage to convert remote file is below. You should use ConvertApiFileParam class to pass file as remote file url wrapped into Uri object.
var convertApi = new ConvertApi("secret");
var sourceFile = new Uri("https://github.com/Baltsoft/CDN/raw/master/cara/testfiles/presentation2.pptx");
var convertToPdf = convertApi.ConvertAsync("pptx", "pdf", new ConvertApiFileParam(sourceFile));

How to access secure url using webclient

I am trying to access secure url via web client and getting few errors.
Overall purpose is download an image from secure url..
Please note that earlier, I was able to download image from repository with http and now they have enforced (security) https in same url.
We have a console application which runs on periodic basis and pulls image from server and stores locally.
Please advise as what I am doing wrong ? or what is missing ?
Following are the issues I am facing.
/// if I use code section 1... I get error saying Parameter is not valid.
/// if I use code section 2... File gets saved to local but get a message " File appear to be corrupt or large and not able to open.
Section 1 and 2 are listed below.
using (WebClient webClient = new WebClient())
{
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
webClient.Credentials = new NetworkCredential("id", "pwd"); // if credentials are wrong...still I get the imageByte
/// section 1 - if I use this code... I get error saying Parameter is not valid.
// ----------------------------- Start --------------------------------
imageByte = webClient.DownloadData("https://someurl/source/abcd.jpeg");
////Initialize image variable
Image newImage;
////Read image data into a memory stream
using (MemoryStream ms = new MemoryStream(imageByte, 0, imageByte.Length, true))
{
ms.Write(imageByte, 0, imageByte.Length);
//Set image variable value using memory stream.
newImage = Image.FromStream(ms, true, false); // Throws error at this line saying that parameter is not valid.
}
newImage.Save(#"location\image.jpeg");
// ----------------------------- End --------------------------------
/// section 2 - if I use this code... File gets saved to local but get a message " File appear to be corrupt or large and not able to open.
// ----------------------------- Start --------------------------------
webClient.DownloadFile("https://someurl/source/abcd.jpeg", #"location\image.jpeg");
// ----------------------------- End --------------------------------
}
Both errors say that the data which was downloaded is not a valid JPEG image. Likely it is because some error was returned from the server.
In order to check if server returned an error, you can take a look at what's in HTTP response headers and body.
For body you can just try to open a file saved in section 2 with a text editor.
For headers you can check webClient.ResponseHeaders property with debugger or with a simple update to your program.
Example below is taken from MSDN:
// Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders;
Console.WriteLine("\nDisplaying the response headers\n");
// Loop through the ResponseHeaders and display the header name/value pairs.
for (int i=0; i < myWebHeaderCollection.Count; i++)
{
Console.WriteLine ("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i));
}
Another ways to see what was actually returned from the server are Invoke-WebRequest PowerShell cmdlet or wget utility (both should support HTTPS and authentication)
You're code works fine.
As Kel suggested most likely the server response header give may give an answer. Are you sure the server is configured to support https?
There is no need to give network credentials. Since HTTPS only is a transport protocol. It secures only the connection.
To do authentication you have to configure the server for example to do BASIC or DIGEST authentication. And if required setup authorization to the requested resource.
One comment on you're code: Don't forget to dispose newImage.

Why does WebClient.UploadValues overwrites my html web page?

I'm familiar with Winform and WPF, but new to web developing. One day saw WebClient.UploadValues and decided to try it.
static void Main(string[] args)
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
//A single file that contains plain html
var response = client.UploadValues("D:\\page.html", values);
var responseString = Encoding.Default.GetString(response);
Console.WriteLine(responseString);
}
Console.ReadLine();
}
After run, nothing printed, and the html file content becomes like this:
thing1=hello&thing2=world
Could anyone explain it, thanks!
The UploadValues method is intended to be used with the HTTP protocol. This means that you need to host your html on a web server and make the request like that:
var response = client.UploadValues("http://some_server/page.html", values);
In this case the method will send the values to the server by using application/x-www-form-urlencoded encoding and it will return the response from the HTTP request.
I have never used the UploadValues with a local file and the documentation doesn't seem to mention anything about it. They only mention HTTP or FTP protocols. So I suppose that this is some side effect when using it with a local file -> it simply overwrites the contents of this file with the payload that is being sent.
You are using WebClient not as it was intended.
The purpose of WebClient.UploadValues is to upload the specified name/value collection to the resource identified by the specified URI.
But it should not be some local file on your disk, but instead it should be some web-service listening for requests and issuing responces.

The remote server returned an error: (550) File unavailable(Error occured on making ftp directory)

I am developing a wpf application and I want to make a directory on ftp using C# with different usernames and if it already exists then save files on existing directory.
I've successfully created the logic of checking the existing directory but while creating a new directory I've got an exception on runtime:
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
I've checked different solutions on the internet and most are saying that it is due to write permissions. I am assigning the ftp folder write permissions, but I am still having the problem. Please Help?
Here is my code:
static void CreateFtpFolder(string source)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(source);
request.Credentials = new NetworkCredential(ftpusername, ftppassword);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.UsePassive = true;
request.UseBinary = false;
request.KeepAlive = false;
request.Proxy = null;
FtpWebResponse ftpResp = request.GetResponse() as FtpWebResponse;
}
I am having the error on FtpWebResponse.
Your code look fine.......you are saying that you have assigned permission too.
The only problem is that you may be passing a wrong "Source"which is causing problem..Check your source string it may have an error......
path should be like
WebRequest request = WebRequest.Create("ftp://host.com/directory123");
it mean directory will be created with name "directory12"
if your are specifying path like this
WebRequest request = WebRequest.Create("ftp://host.com/directory123/directory1234");
this mean "ftp://host.com/directory123/" should already exist and new directory will be created with name "directory1234"
hope it will help
If the problem is a Windows Server-side permission issue and you have access to this FTP server, you may be able to resolve it by modifying the permission and adding 'Write' permission for the username that you are authenticating with on the actual physical directory.
e.g. If 'ftp://host/' points to 'c:\inetpub\ftproot' on your server, then allow 'Write' permission for the user on that directory.
I was setting up my own IIS 7 FTP server and spent a good hour or two trying to get such a simple snippet of C# client code to work, so thought I'd contribute for those in similar situations.
You get that error if the directory already exists. Pretty non-descriptive error message (lol). Must put a try catch around the call to request.GetResponse()
try
{
FtpWebResponse ftpResp = request.GetResponse() as FtpWebResponse;
}
catch ( Exception ex ) { /* ignore */ }

Invoking another URL

string url = "http://foo.com/bar?id=" + id + "&more=" + more;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
I m trying make a call to another server, and getting back the following:
|FATAL|The remote server returned an error: (406) Not Acceptable. (REF #1)
System.Net.WebException: The remote server returned an error: (406) Not Acceptable.
Why am i getting this error? and how to fix this?
According to the RFC
10.4.7 406 Not Acceptable
The resource identified by the request
is only capable of generating response
entities which have content
characteristics not acceptable
according to the accept headers sent
in the request.
Review the accept headers that your request is sending , and the content server in that URL ; )
BONUS
To see the accept headers: browse to
the URL and use FireBug (HTML tab).
To set the accept headers into your
request use the HttpWebRequest
Members.

Categories