No response when using WebClient.UploadFile - c#

I'm uploading a file using the UploadFile method on the WebClient object. When the file is uploaded I would like to get a confirmation and according to MSDN (and also here on stackoverflow: Should I check the response of WebClient.UploadFile to know if the upload was successful?) I should be able to read the returned byte array but that is always empty.
Am I doing something the wrong way?
WebClient FtpClient = new WebClient();
FtpClient.Credentials = new NetworkCredential("test", "test");
byte[] responseArray = FtpClient.UploadFile("ftp://localhost/Sample.rpt", #"C:\Test\Sample.rpt");
string s = System.Text.Encoding.ASCII.GetString(responseArray);
Console.WriteLine(s); //Empty string
Or is it always successful if it doesn't return an exception?

Answer to myself: I couldn't make any sense of it so i switched to edt ftp (http://www.enterprisedt.com/) instead.

Related

How can i search a hebrew word from a website using c#

Im trying to search a Hebrew word in a website using c# but i cant figure it out.
this is my current state code that im trying to work with:
var client = new WebClient();
Encoding encoding = Encoding.GetEncoding(1255);
var text = client.DownloadString("http://shchakim.iscool.co.il/default.aspx");
if (text.Contains("ביטול"))
{
MessageBox.Show("idk");
}
thanks for any help :)
The problem seems to be that WebClient is not using the right encoding when converting the response into a string, you must set the WebClient.Encoding property to the expected encoding from the server for this conversion to happen correctly.
I inspected the response from the server and it's encoded using utf-8, the updated code below reflects this change:
using (var client = new WebClient())
{
client.Encoding = System.Text.Encoding.UTF8;
var text = client.DownloadString("http://shchakim.iscool.co.il/default.aspx");
// The response from the server doesn't contains the word ביטול, therefore, for demo purposes I changed it for שוחרות which is present in the response.
if (text.Contains("שוחרות"))
{
MessageBox.Show("idk");
}
}
Here you can find more information about the WebClient.Encoding property:
https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.encoding?view=netframework-4.7.2
Hope this helps.

Howto: download a file keeping the original name in C#?

I have files on a server that can be accessed from a URL formatted like this:
http:// address/Attachments.aspx?id=GUID
I have access to the GUID and need to be able to download multiple files to the same folder.
if you take that URL and throw it in a browser, you will download the file and it will have the original file name.
I want to replicate that behavior in C#. I have tried using the WebClient class's DownloadFile method, but with that you have to specify a new file name. And even worse, DownloadFile will overwrite an existing file. I know I could generate a unique name for every file, but i'd really like the original.
Is it possible to download a file preserving the original file name?
Update:
Using the fantastic answer below to use the WebReqest class I came up with the following which works perfectly:
public override void OnAttachmentSaved(string filePath)
{
var webClient = new WebClient();
//get file name
var request = WebRequest.Create(filePath);
var response = request.GetResponse();
var contentDisposition = response.Headers["Content-Disposition"];
const string contentFileNamePortion = "filename=";
var fileNameStartIndex = contentDisposition.IndexOf(contentFileNamePortion, StringComparison.InvariantCulture) + contentFileNamePortion.Length;
var originalFileNameLength = contentDisposition.Length - fileNameStartIndex;
var originalFileName = contentDisposition.Substring(fileNameStartIndex, originalFileNameLength);
//download file
webClient.UseDefaultCredentials = true;
webClient.DownloadFile(filePath, String.Format(#"C:\inetpub\Attachments Test\{0}", originalFileName));
}
Just had to do a little string manipulation to get the actual filename. I'm so excited. Thanks everyone!
As hinted in comments, the filename will be available in Content-Disposition header. Not sure about how to get its value when using WebClient, but it's fairly simple with WebRequest:
WebRequest request = WebRequest.Create("http://address/Attachments.aspx?id=GUID");
WebResponse response = request.GetResponse();
string originalFileName = response.Headers["Content-Disposition"];
Stream streamWithFileBody = response.GetResponseStream();

Url request on RichTextBox?

I want to get HTML code to be displayed in a RichTextBox. I am using the code
WebClient client = new WebClient();
byte[] data = client.DownloadData("http://www.google.com");
richTextBox1.Text = data.ToString();
How can I do this?
Also: I don't know why but this shows me "System.Byte[]" on the RichTextBox.
Use WebClient.DownloadString that downloads the specified resource as a String or a Uri:
var contents = new System.Net.WebClient().DownloadString(url);
Note that: RTF encoding is different from HTML. You cannot do this straight away. I suggest WebBrowser control.
or try this ways:
http://www.codeproject.com/KB/HTML/XHTML2RTF.aspx
http://www.codeproject.com/KB/edit/htmlrichtextbox.aspx
It shows System.Byte[] Because it is show the description of data, not data's contents. to do this do something like:
WebClient client = new WebClient();
byte[] file = client.DownloadData("example.com");
File.WriteAllBytes(#"example.txt", file);
string[] lines = File.ReadAllLines("example.txt");
richTextBox1.Text = lines;
To see the actual content
EDIT
Or you can do WebClient.DownloadString like #Ria Suggested. Only I would implement it like this:
WebClient client = new WebClient();
var data = client.DownloadString("example.com");
richTextBox1.Text = data.ToString();
Or to be more efficient even
richTextBox1.Text = client.DownloadString("example.com");

WebClient set headers

How I can set a header in the webClient class?
I tried:
client.Headers["Content-Type"] = "image/jpeg";
that throws a WebException
My code:
WebClient client = new WebClient();
client.Headers.Set("Content-Type", "image/png");
client.Headers.Set("Content-Length", length);
client.Headers.Add("Slug", name);
NameValueCollection nvc = new NameValueCollection();
nvc.Add("file", FileContents);
Byte[] data = client.UploadValues(url, nvc);
string res = Encoding.ASCII.GetString(data);
Response.Write(res);
If the header already exists:
client.Headers.Set("Content-Type", "image/jpeg");
if its a new header:
client.Headers.Add("Content-Type", "image/jpeg");
Also, there is a chance that you are getting an error because you are trying to set the headers too late. Post your exception so we can let you know.
Update
Looks like there are some weird restrictions on the "Content-Type" header with the WebClient class. Look in to using the client.Download methods (DownloadData, DownloadFile, etc...)
See if using the "UploadFile" method on webclient works rather than doing it manually. It returns the respose body byte[].
If you continue to have issues with the WebClient, try justing using a plain old HttpRequest/HttpWebRequest.
It seems you can not set Content-type with WebClient.UploadValues method. You could set Content-type with WebClient.UploadData method
Use something like,
Client.Headers["Content-Type"] = "application/json";
Client.UploadData("http://www.imageshack.us/upload_api.php", "POST", Encoding.Default.GetBytes("{\"Data\": \"Test\"}"));
Have you tried this syntax: client.Headers.Add("Content-Type", "image/jpeg");
What's your stack trace? At what point are you setting this? And what version of IIS/OS are you running under?
You cannot change the Content-Type if you use the UploadValues method, it must be application/x-www-form-urlencoded, see webclient source code

Bytes Upload to the server:

In my application I use below code to upload a file to the server.
response = (HttpWebResponse)request.GetResponse();
where request.Method is "PUT".
Is there a way to get the number of bytes uploaded to the server.
Thanks in advance
Is HttpWebResponse.ContentLength suitable?
why you can't try with WebClient
E.g:
WebClient wc = new WebClient();
byte[] s = wc.UploadFile("string address", "string fileName");

Categories

Resources