Intercepting requested file path & Open file from different source in new tab - c#

I have 4.7.2 application where on anchor tag we have file link like 'www.abc.com/a.txt'. If I click it file is opening in new tab.
But now expected result is - When user hit that link, I want to intercept this link & change it to 'www.xyz.com/a.txt' & return response in new tab. Basically open file in new tab (no download).
Currently I'm able to download file using below code but I want to open in new tab.
Stream stream = null;
int bytesToRead = 10000;
byte[] buffer = new Byte[bytesToRead];
try
{
string apiGatewayFilePath = "www.xyz.com/a.txt";
HttpWebRequest fileReq = (HttpWebRequest)WebRequest.Create(apiGatewayFilePath);
string fileName = Path.GetFileName(apiGatewayFilePath);
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
stream = fileResp.GetResponseStream();
var resp = HttpContext.Current.Response;
resp.ContentType = MediaTypeNames.Application.Octet;
resp.AddHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
if (resp.IsClientConnected)
{
length = stream.Read(buffer, 0, bytesToRead);
resp.OutputStream.Write(buffer, 0, length);
resp.Flush();
buffer = new Byte[bytesToRead];
}
else
{
length = -1;
}
} while (length > 0);
}
finally
{
if (stream != null)
{
stream.Close();
}
}

Related

Unable to download the PDF file from URL

I need to download an .PDF file from a website : https://XXXXX/XXXX/XXXXXXX.pdf when user click's on link button. Below code is working fine in local but when I try to click on link button for downloading the file after deploying into server, First time it is working fire but next consecutive downloads, It is displaying as The XXXX.PDF download was interrupted or file cannot be downloaded.
try
{
string fullFileName =string.Empty;
LinkButton btn = (LinkButton)(sender);
string filepath = btn.CommandArgument;
string fileName = btn.Text;
if (fileName != null && !string.IsNullOrEmpty(fileName))
{
fullFileName = filePath +fileName ;
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
//string fileName = System.IO.Path.GetFileName(fullFileName);
//Create a WebRequest to get the file
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls | (SecurityProtocolType)768/*TLS1.1*/ | (SecurityProtocolType)3072/*TLS1.2*/;
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(fullFileName);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/PDF";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
else
{
lblFile.Text = "File Name is missing";
lblFile.Visible = true;
}
}
catch (Exception ex)
{
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
Can someone please guide me why it is failing in server

Can't seek audio files prepared with HTTP source (Android MediaPlayer)

So I'm trying to build some sort of a media player, the application prepares audio from an external source (HTTP server sitting on another device), when trying to seek the MediaPlayer returns "Stream has no duration and is therefore not seekable"
Note: I saw questions about the same error but they were about live streams, this is a static MP3 file.
Code from the other device (the server of the audio files)
private static void WriteFile(HttpListenerContext ctx, Android.Net.Uri uri, Activity activity)
{
var response = ctx.Response;
Debug.Print(ctx.Request.RemoteEndPoint.ToString());
using (var file = activity.ContentResolver.OpenInputStream(uri))
{
string fileName = "Audio.mp3";
ICursor cursor = activity.ContentResolver.Query(uri, null, null, null, null);
try
{
if (cursor != null && cursor.MoveToFirst())
fileName = cursor.GetString(cursor.GetColumnIndex(OpenableColumns.DisplayName));
}
finally
{
cursor.Close();
}
response.SendChunked = false;
response.ContentType = "audio/mpeg";
response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
byte[] buffer = new byte[64 * 1024];
int read;
using (BinaryWriter bw = new BinaryWriter(response.OutputStream))
{
while ((read = file.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write(buffer, 0, read);
bw.Flush();
}
bw.Close();
response.ContentLength64 = bw.BaseStream.Length;
}
response.StatusCode = (int)HttpStatusCode.OK;
response.StatusDescription = "OK";
response.OutputStream.Close();
}
I'm not sure how this code is not throwing a "cannot access a closed stream" exception:
bw.Close();
response.ContentLength64 = bw.BaseStream.Length;
But... retrieve the length before closing the stream:
response.ContentLength64 = bw.BaseStream.Length;
bw.Close();

Download a file with .net compact and C#

I am re-developing an app for a scanner used for stocktakes to allow it to work while offline. In order to do so, I need to be able to download a file from a laptop which is acting as a server. I got to a point at which it works, but only downloads that are of size 9.53mb max. How can I tweak the code to allow for larger files. I would need to allow for a maximum size of around 30mb.
Here is my code:
try
{
string full_url = App.prouductUrl + App.stStocktakeId + ".db";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(full_url);
httpRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
System.IO.Stream dataStream = httpResponse.GetResponseStream();
// Dim str As Stream = cdsMobileLibrary2.http_download.getfile(filename)
//50 meg
byte[] inBuf = new byte[10000001];
int bytesToRead = Convert.ToInt32(inBuf.Length);
int bytesRead = 0;
while (bytesToRead > 0)
{
int n = dataStream.Read(inBuf, bytesRead, bytesToRead);
if (n == 0)
{
break; // TODO: might not be correct. Was : Exit While
}
bytesRead += n;
bytesToRead -= n;
}
FileStream fstr = new FileStream(#"\productdb\" + App.stStocktakeId + ".db", FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
dataStream.Close();
fstr.Close();
string size = loginRes.getFromJSON("size");
FileInfo fi = new FileInfo(#"\productdb\" + App.stStocktakeId + ".db");
MessageBox.Show("File Size is:" + fi.Length + "Compared to:" + size);
}
catch { }

How to download jpg/doc file from my server with Url in asp.net web application

My problem is unable to download file from sever
My code work fine for any Google image-url (eg.:-http://blogs.independent.co.uk/wp-content/uploads/2012/12/google-zip.jpg)
but it is not work in case of my server image-url("eg.:-[http://110.15.445.87/xyz/abc/123.jpg]")
i dont know where is problem
my code is :-
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
String Url = "http://112.196.32.51/ll1/UploadFiles/13062402231250.jpg";
//String Url = "http://blogs.independent.co.uk/wp-content/uploads/2012/12/google-zip.jpg";
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
String fileName = "Rock.jpg";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
}

Download a File From a External sever through Asp.net & C#

First,I uploaded a file in a external server and got a url from that server.Now i want to download that uploaded file from the external server through that url which i got from that server through asp.net and c#.
I wrote a c# code to download that file, but during that process i got an exception
"Exception of type 'System.OutOfMemoryException' was thrown".
The following is the c# code which i wrote to download:
double dlsize=0;
string Url = "http://www.sample.com/download.zip"; \\File Size: 75MB
int lastindex = Url.LastIndexOf("/");
string TempUrlName = Url.Substring(lastindex + 1, Url.Length - (lastindex + 1));
WebRequest oWebRequest = WebRequest.Create(Url);
oWebRequest.Timeout = -1;
WebResponse oWebResponse = oWebRequest.GetResponse();
if (oWebResponse.ContentType != "text/html; charset=UTF-8")
{
string myFile = oWebResponse.Headers.Get("Content-Length");
int TempmyFile = Convert.ToInt32(myFile);
double bytes_total = Convert.ToDouble(TempmyFile);
dlSize = Convert.ToDouble(bytes_total / (1024 * 1024));
System.IO.MemoryStream oMemoryStream = new MemoryStream();
byte[] buffer = new byte[4096];
using (System.IO.Stream oStream = oWebResponse.GetResponseStream())
{
int Count = 0;
do
{
Count = oStream.Read(buffer, 0, buffer.Length);
oMemoryStream.Write(buffer, 0, Count);
} while (Count != 0);
}
System.IO.FileStream oFileStream = new System.IO.FileStream("C:\Documents and Settings\arun\Desktop\New Folder\download.zip", System.IO.FileMode.Create);
oMemoryStream.WriteTo(oFileStream);
oFileStream.Flush();
oFileStream.Close();
oMemoryStream.Flush();
oMemoryStream.Close();
oWebResponse.Close();
}
It would be easier to do it like this:
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);

Categories