Download file using httprequest in C# Code - c#

I am try to download pdf file from below code using webRequest in C# Code.I have tried below code but no error and no output is showing.Please check this below code and advise how to do this...
Note:
PlayResponeAsync method is not executing When I debug
I am using .Net framework 4.0
private static void DownloadCurrent() {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://einvoicing
.internal.cleartax.co/v2/eInvoice/download?
irns=11eaf48a909dda520db27ff35804d4b42df2c3b6285afee8df586cc4dbd10541");
webRequest.Method = "GET";
webRequest.ContentType = "application/pdf";
webRequest.Headers.Add("owner_id", "78c6beda-54a2-11ea-b064-0af3f8b02c24");
webRequest.Headers.Add("gstin", "29AAFCD5862R000");
webRequest.Timeout = 3000;
webRequest.BeginGetResponse(new AsyncCallback(PlayResponeAsync), webRequest);
}
private static void PlayResponeAsync(IAsyncResult asyncResult) {
long total = 0;
long received = 0;
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
try {
using (HttpWebResponse webResponse =
(HttpWebResponse)webRequest.EndGetResponse(asyncResult)) {
byte[] buffer = new byte[1024];
FileStream fileStream = File.OpenWrite("[file name to write]");
using (Stream input = webResponse.GetResponseStream()) {
total = input.Length;
int size = input.Read(buffer, 0, buffer.Length);
while (size > 0) {
fileStream.Write(buffer, 0, size);
received += size;
size = input.Read(buffer, 0, buffer.Length);
}
}
fileStream.Flush();
fileStream.Close();
}
}
catch (Exception ex) { }
}

Related

Bot Framework - Using Custom Speech Service Error 400 C#

I created a bot with bot framework and now i'm trying to use the CustomSpeech service instead of the bing SpeechToText Service that works fine. I have tried various way to resolve the problem but i get the error 400 and i don't know how to solve this.
The method where i would like to get the text from a Stream of a wav pcm audio:
public static async Task<string> CustomSpeechToTextStream(Stream audioStream)
{
audioStream.Seek(0, SeekOrigin.Begin);
var customSpeechUrl = "https://westus.stt.speech.microsoft.com/speech/recognition/interactive/cognitiveservices/v1?cid=<MyEndPointId>";
string token;
token = GetToken();
HttpWebRequest request = null;
request = (HttpWebRequest)HttpWebRequest.Create(customSpeechUrl);
request.SendChunked = true;
//request.Accept = #"application/json;text/xml";
request.Method = "POST";
request.ProtocolVersion = HttpVersion.Version11;
request.ContentType = "audio/wav; codec=\"audio/pcm\"; samplerate=16000";
request.Headers["Authorization"] = "Bearer " + token;
byte[] buffer = null;
int bytesRead = 0;
using (Stream requestStream = request.GetRequestStream())
{
// Read 1024 raw bytes from the input audio file.
buffer = new Byte[checked((uint)Math.Min(1024, (int)audioStream.Length))];
while ((bytesRead = audioStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Flush();
}
string responseString = string.Empty;
// Get the response from the service.
using (WebResponse response = request.GetResponse()) // Here i get the error
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
}
dynamic deserializedResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString);
if (deserializedResponse.RecognitionStatus == "Success")
{
return deserializedResponse.DisplayText;
}
else
{
return null;
}
}
At using (WebResponse response = request.GetResponse()){} i get an exception (Error 400).
Am I doing the HttpWebRequest in the right way?
I read in internet that maybe the problem is the file audio... but then why with the same Stream bing speech service doesn't return this error?
In my case the problem was that i had a wav stream audio that doesn't had the file header that Cris (Custom Speech Service) needs. The sulution is creating a temporary file wav, read the file wav and copy it in a Stream to send it as array to Cris
byte[] buffer = null;
int bytesRead = 0;
using (Stream requestStream = request.GetRequestStream())
{
buffer = new Byte[checked((uint)Math.Min(1024, (int)audioStream.Length))];
while ((bytesRead = audioStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Flush();
}
or copy it in a MemoryStream and send it as array
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(audioStream.ToArray(), 0, audioStream.ToArray().Length);
requestStream.Flush();
}

How to upload many text files from local computer to ftp using c# .net?

I need to upload text file from local machine to ftp server using c#.
I've tried folowing code but it did't work.
private bool UploadFile(FileInfo fileInfo)
{
FtpWebRequest request = null;
try
{
string ftpPath = "ftp://www.tt.com/" + fileInfo.Name
request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.Credentials = new NetworkCredential("ftptest", "ftptest");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = false;
request.Timeout = 60000; // 1 minute time out
request.ServicePoint.ConnectionLimit = 15;
byte[] buffer = new byte[1024];
using (FileStream fs = new FileStream(fileInfo.FullPath, FileMode.Open))
{
int dataLength = (int)fs.Length;
int bytesRead = 0;
int bytesDownloaded = 0;
using (Stream requestStream = request.GetRequestStream())
{
while (bytesRead < dataLength)
{
bytesDownloaded = fs.Read(buffer, 0, buffer.Length);
bytesRead = bytesRead + bytesDownloaded;
requestStream.Write(buffer, 0, bytesDownloaded);
}
requestStream.Close();
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
request = null;
}
return false;
}// UploadFile
any suggestions ???
You need to actually send the request by calling GetResponse().
You can also make your code much simpler by calling fs.CopyTo(requestStream).
I tinkered around with a bit ftp code and got the following, which seems to work pretty well for me.
ftpUploadloc is a ftp://ftp.yourftpsite.com/uploaddir/yourfilename.txt
ftpUsername and ftpPassword should be self explanatory.
Finally currentLog is the location of the file you're uploading.
Let me know how this worked out for you, if anyone else has any other suggestions I welcome those.
private void ftplogdump()
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUploadloc);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
StreamReader sourceStream = new StreamReader(currentLog);
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();
// Remove before publishing
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}

How To Use HttpWebRequest/Response To Download A Binary (.exe) File From A Web Server?

I am writing a program that needs to download an .exe file from a website and then save it to the hard drive. The .exe is stored on my site and it's url is as follows (it's not the real uri just one I made up for the purpose of this question):
http://www.mysite.com/calc.exe
After many web searches and fumbling through examples here is the code I have come up with so far:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(http://www.mysite.com/calc.exe);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string s = streamReader.ReadToEnd();
As you can see I am using the StreamReader class to read the data. After calling ReadToEnd does the stream reader contain the (binary) content of my .exe? Can I just write the content of the StreamReader to a file (named calc.exe) and I will have succesfully downloaded the .exe?
I am wondering why StreamReader ReadToEnd returns a string. In my case would this string be the binary content of calc.exe?
WebClient is the best method to download file. But you can use the following method to download a file asynchronously from web server.
private static void DownloadCurrent()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("[url to download]");
webRequest.Method = "GET";
webRequest.Timeout = 3000;
webRequest.BeginGetResponse(new AsyncCallback(PlayResponeAsync), webRequest);
}
private static void PlayResponeAsync(IAsyncResult asyncResult)
{
long total = 0;
long received = 0;
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
try
{
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
byte[] buffer = new byte[1024];
FileStream fileStream = File.OpenWrite("[file name to write]");
using (Stream input = webResponse.GetResponseStream())
{
total = input.Length;
int size = input.Read(buffer, 0, buffer.Length);
while (size > 0)
{
fileStream.Write(buffer, 0, size);
received += size;
size = input.Read(buffer, 0, buffer.Length);
}
}
fileStream.Flush();
fileStream.Close();
}
}
catch (Exception ex)
{
}
}
There is a similar thread here - how to download the file using httpwebrequest
StreamReader is a text reader implementation i.e. it should be used to read text data and not binary data. In your case, you should be directly using the underlying response stream.
For downloading file, the simplest way would be to use WebClient.DownloadFile method.
This should directly save the file on your hard disk.
using System.Net;
using (WebClient webClient = new WebClient ())
{
webClient.DownloadFile("http://www.mysite.com/calc.exe", "calc.exe");
}
Instead of using StreamReader, you should really call Read() method of your Stream object. That will ask you for a byte[] buffer to be fill with read data, which you can then write to disk using StreamWriter or FileStream.
I'm probably a little bit late but I had the same problem with files being always 0kb big if not running in Debug mode.. This might be a relatively simple answer but disabling "DEBUG-Constants" under Properties solved it for me.
I have created a class with events so you can track download progress:
using System;
using System.IO;
using System.Net;
using System.Net.Mime;
//event examples: https://www.tutorialsteacher.com/csharp/csharp-event
public class HttpWebRequestDownload
{
private long _totalBytesLength = 0;
private long _transferredBytes = 0;
private int _transferredPercents => (int)((100 * _transferredBytes) / _totalBytesLength);
private string _defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
public string downloadedFilePath = String.Empty;
public HttpWebRequestDownload(){
//Windows 7 fix
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
}
public void DownloadFile(string url, string destinationDirectory = default)
{
string filename = "";
if (destinationDirectory == default)
destinationDirectory = _defaultDirectory;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Cache-Control", "no-store");
request.Headers.Add("Cache-Control", "max-age=1");
request.Headers.Add("Cache-Control", "s-maxage=1");
request.Headers.Add("Pragma", "no-cache");
request.Headers.Add("Expires", "-1");
if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result)
{
_totalBytesLength = response.ContentLength;
string path = response.Headers["Content-Disposition"];
if (string.IsNullOrWhiteSpace(path))
{
var uri = new Uri(url);
filename = Path.GetFileName(uri.LocalPath);
}
else
{
ContentDisposition contentDisposition = new ContentDisposition(path);
filename = contentDisposition.FileName;
}
using (Stream responseStream = response.GetResponseStream())
using (FileStream fileStream = File.Create(System.IO.Path.Combine(destinationDirectory, filename)))
{
byte[] buffer = new byte[1024*1024]; // 1MB buffer
ProgressEventArgs eventArgs = new ProgressEventArgs(_totalBytesLength);
int size = responseStream.Read(buffer, 0, buffer.Length);
while (size > 0)
{
fileStream.Write(buffer, 0, size);
_transferredBytes += size;
size = responseStream.Read(buffer, 0, buffer.Length);
eventArgs.UpdateData(_transferredBytes, _transferredPercents);
OnDownloadProgressChanged(eventArgs);
}
}
}
downloadedFilePath = Path.Combine(destinationDirectory, filename);
OnDownloadFileCompleted(EventArgs.Empty);
}
catch (Exception e)
{
OnError($"{e.Message} => {e?.InnerException?.Message}");
}
}
//events
public event EventHandler<ProgressEventArgs> DownloadProgressChanged;
public event EventHandler DownloadFileCompleted;
public event EventHandler<string> Error;
public class ProgressEventArgs : EventArgs
{
public long TransferredBytes { get; set; }
public int TransferredPercents { get; set; }
public long TotalBytesLength { get; set; }
public ProgressEventArgs(long transferredBytes, int transferredPercents, long totalBytesLength)
{
TransferredBytes = transferredBytes;
TransferredPercents = transferredPercents;
TotalBytesLength = totalBytesLength;
}
public ProgressEventArgs(long totalBytesLength)
{
this.TotalBytesLength = totalBytesLength;
}
public void UpdateData(long transferredBytes, int transferredPercents)
{
TransferredBytes = transferredBytes;
TransferredPercents = transferredPercents;
}
}
protected virtual void OnDownloadProgressChanged(ProgressEventArgs e)
{
DownloadProgressChanged?.Invoke(this, e);
}
protected virtual void OnDownloadFileCompleted(EventArgs e)
{
DownloadFileCompleted?.Invoke(this, e);
}
protected virtual void OnError(string errorMessage)
{
Error?.Invoke(this, errorMessage);
}
}
Here is testing example:
static void Main(string[] args)
{
HttpWebRequestDownload hDownload = new HttpWebRequestDownload();
string downloadUrl = "http://speedtest.tele2.net/10MB.zip";
hDownload.DownloadProgressChanged += HDownloadOnDownloadProgressChanged;
hDownload.DownloadFileCompleted += delegate(object o, EventArgs args)
{
Debug.WriteLine("Download finished and saved to: "+hDownload.downloadedFilePath);
};
hDownload.Error += delegate(object o, string errMessage) { Debug.WriteLine("Error has occured !! => "+errMessage); };
hDownload.DownloadFile(downloadUrl);
}
private void HDownloadOnDownloadProgressChanged(object sender, HttpWebRequestDownload.ProgressEventArgs e)
{
Debug.WriteLine("progress: "+e.TransferredBytes+" => "+e.TransferredPercents);
}

Download a file from a form post

I have a c# script that does 2 things
This script connects a my web server to get a pin number generated,
It then makes a connection where its post a form with that pin number it gets from my web server,
The problem is when the form is posted it responds with an application now i need to run this application i don't care if i have to save the exe then run it or if i can run it from memory
Here is my script sofar
string[] responseSplit;
bool connected = false;
try
{
request = (HttpWebRequest)WebRequest.Create(API_url + "prams[]=");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
connected = true;
}
catch(Exception e)
{
MessageBox.Show(API_url + "prams[]=");
}
if (!connected)
{
MessageBox.Show("Support Requires and Internet Connection.");
}
else
{
request = (HttpWebRequest)WebRequest.Create(API_url + "prams[]=");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string responceString = reader.ReadToEnd();
responseSplit = responceString.Split('\n');
WebRequest req = WebRequest.Create("https://secure.logmeinrescue.com/Customer/Code.aspx");
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes("Code=" + responseSplit[1]);
req.ContentLength = bytes.Length;
Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
WebResponse responce = req.GetResponse();
hasDownloaded = true;
}
Well you could save the response into a file and then run it (assuming it's an executable of course):
using (var response = req.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var output = new FileStream("test.exe", FileMode.Create, FileAccess.Write))
{
var buffer = new byte[2048]; // read in chunks of 2KB
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
Process.Start("test.exe");

HttpWebResponse send to web browser?

I am new to c# and am making a simple proxy to edit certain headers.
I have used HttpLisenter to get the request and then used HttpWebRequest and Response to edit, send and receive.
Now I need some help to send the edited response back to the web browser. Does anyone have any links or examples? Im stumped :)
Thanks
Here's a short example:
public void ProcessRequest(HttpContext context)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create([NEW_URL]);
request.Timeout = 1000 * 60 * 60;
request.Method = context.Request.HttpMethod;
if (request.Method.ToUpper() == "POST")
{
Stream sourceInputStream = context.Request.InputStream;
Stream targetOutputStream = request.GetRequestStream();
sourceInputStream.CopyTo(targetOutputStream);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
context.Response.ContentType = request.ContentType;
using (response)
{
Stream targetInputStream = response.GetResponseStream();
Stream sourceOutputStream = context.Response.OutputStream;
targetInputStream.CopyTo(sourceOutputStream);
}
}
This assume the following extension method is defined (I think using this makes the sample more readable):
public static void CopyTo(this Stream input, Stream output)
{
using (input)
using (output)
{
byte[] buffer = new byte[1024];
for (int amountRead = input.Read(buffer, 0, buffer.Length); amountRead > 0; amountRead = input.Read(buffer, 0, buffer.Length))
{
output.Write(buffer, 0, amountRead);
}
}
}
You could save the response to an html file and then start the browser with a command to open the file.
class Program
{
static int Main() {
WebRequest wr = HttpWebRequest.Create("http://google.com/");
HttpWebResponse wresp = (HttpWebResponse)wr.GetResponse();
string outFile = #"c:\tmp\google.html";
using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
{
using(StreamWriter sw = new StreamWriter(outFile, false)) {
sw.Write(sr.ReadToEnd());
}
}
BrowseFile(outFile);
return 0;
}
static void BrowseFile(string filePath)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
startInfo.Arguments = filePath;
Process.Start(startInfo);
}
}
Take a look at source code for existing proxy servers.
Mini Proxy Server (c#)
Web Proxy Server (c#)

Categories