Bytes Upload to the server: - c#

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");

Related

Not found error when using WebClient to send a GET request

I'm trying to send GET request to my server, using WebClient and get error for "Not found". In C++ the same request works fine. My URL looks like:
"https://www.example.com/something/something&param1=data1&param2={}"
... and the request look like
WebClient client = new WebClient();
string res = client.DownloadString(url);
What am I doing wrong?
I succeeded! i was missing the headers.
my URL looks like "https://www.example.com/something/something?param1=data1&param2={}"
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Accept-Version", "4");
client.Headers.Add("User-Agent", "v4.1.0.0");
string res = client.DownloadString(url);
Thanks for the help

Saving a GIF from a URL

I want to save a GIF driven from an internet address.
When I request the file from the browser, I receive these characters:
GIF87a½€ÿÿÿ,½þ„©Ëí£œ´Ú‹³Þ¼û†âH–æ‰Ádk
ÇòòµuÏú>æùôãEX¯–Š¨²µ‚‰"<}O)Ò¨¬:kÜ'Õª]þ¢`ìc
­Ú”ìvöhe;Ï]¸;oßÂyþ|Þ‡µe§'hÄÔdhW÷§H#&gö¨ð…G™Gy(‰ x÷j†øyÙˆI8uJZZiª
™ªÚº¹i {ç‰Zj™ˆwšµ7
©;é›9Æy¤VÄ$ú;œË›ÙÛI¬,œ=}|,l¼Û˧¸ìæ%]h~n»8»ÌíIv—Fe6¿‹¸®0YÉ
J7k8”•pÕá C¬4Èráâ;zü2¤È‘$Kš
Can I retrieve GIF format with these characters?
A GIF is a binary file. You shouldn't be reading it as a string. Read the GIF into a byte[], and then save those bytes to a file.
Just do this:
string url = "http://address.com/getFile?s=1234";
string filePath = #"c:\MyFolder\file.gif";
using (WebClient client = new WebClient())
{
client.DownloadFile(url, filePath);
}
and do not forget to add this at the beginning:
using System.Net;
thanks for your answers.
I've tried a way and I found the Issue
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Accept = "text/html, text/plain";
request.AllowAutoRedirect = true;
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
Bitmap bmp = new Bitmap(Image.FromStream(stream, true, false));
bmp.Save("image.gif");
Judging from what I know about file formats and the web, the characters are representations ASCII or another encoding of binary. You may still be able to save it using the BinaryWriter.Write() Method.

No response when using WebClient.UploadFile

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.

How can I get file from FTP (using C#)?

Now I know how to copy files from one directory to another, this is really simple.
But now I need to do the same with files from FTP server. Can you give me some example how to get file from FTP while changing its name?
Take a look at How to: Download Files with FTP or downloading all files in directory ftp and c#
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// 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("Download Complete, status {0}", response.StatusDescription);
reader.Close();
reader.Dispose();
response.Close();
Edit
If you want to rename file on FTP Server take a look at this Stackoverflow question
Easiest way
The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile.
It takes an URL to the source remote file and a path to the target local file. So you can use a different name for the local file, if you need that.
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
"ftp://ftp.example.com/remote/path/file.zip", #"C:\local\path\file.zip");
Advanced options
If you need greater control, that WebClient does not offer (like TLS/SSL encryption, ASCII mode, active mode, etc), use FtpWebRequest. Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(#"C:\local\path\file.zip"))
{
ftpStream.CopyTo(fileStream);
}
Progress monitoring
If you need to monitor a download progress, you have to copy the contents by chunks yourself:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(#"C:\local\path\file.zip"))
{
byte[] buffer = new byte[10240];
int read;
while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, read);
Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
}
}
For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar
Downloading folder
If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

Using ftp in C# to send a file

I'm trying to send a file using ftp. I have the following code:
string server = "x.x.x.x"; // Just the IP Address
FileStream stream = File.OpenRead(filename);
byte[] buffer = new byte[stream.Length];
WebRequest request = WebRequest.Create("ftp://" + server);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
Stream reqStream = request.GetRequestStream(); // This line fails
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
But when I run it, I get the following error:
The requested URI is invalid for this FTP command.
Please can anyone tell me why? Am I using this incorrectly?
I think you need to specify the path and filename you're uploading too, so I think it should be either of:
WebRequest request = WebRequest.Create("ftp://" + server + "/");
WebRequest request = WebRequest.Create("ftp://" + server + "/filename.ext");
When I had to use ftp method, I had to set some flags on request object, without it the function did not work:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.KeepAlive = true/false;
request.UsePassive = true/false;
request.UseBinary = xxx;
These flags depend on the server, if you have no access to the server then you cannot know what to use here, but you can test and see what works in your configuration.
And file name is probably missing at the end of URI, so that the server knows where to save uploaded file.

Categories

Resources