I am downloading image files from web using the following code in my Console Application.
WebClient client = new WebClient();
client.DownloadFile(string address_of_image_file,string filename);
The code is running absolutely fine.
I want to know if there is a way i can get the size of this image file before I download it.
PS- Actually I have written code to make a crawler which moves around the site downloading image files. So I doesn't know its size beforehand. All I have is the complete path of file which has been extracted from the source of webpage.
Here is a simple example you can try
if you have files of different extensions like .GIF, .JPG, etc
you can create a variable or wrap the code within a Switch Case Statement
System.Net.WebClient client = new System.Net.WebClient();
client.OpenRead("http://someURL.com/Images/MyImage.jpg");
Int64 bytes_total= Convert.ToInt64(client.ResponseHeaders["Content-Length"])
MessageBox.Show(bytes_total.ToString() + " Bytes");
If the web-service gives you a Content-Length HTTP header then it will be the image file size. However, if the web-service wants to "stream" data to you (using Chunk encoding), then you won't know until the whole file is downloaded.
You can use this code:
using System.Net;
public long GetFileSize(string url)
{
long result = 0;
WebRequest req = WebRequest.Create(url);
req.Method = "HEAD";
using (WebResponse resp = req.GetResponse())
{
if (long.TryParse(resp.Headers.Get("Content-Length"), out long contentLength))
{
result = contentLength;
}
}
return result;
}
You can use an HttpWebRequest to query the HEAD Method of the file and check the Content-Length in the response
You should look at this answer: C# Get http:/…/File Size where your question is fully explained. It's using HEAD HTTP request to retrieve the file size, but you can also read "Content-Length" header during GET request before reading response stream.
Related
I'm trying to get a link from a pastebin. Where the link is the only text in the raw paste. Then I want to download a file from the link in pastebin.
WebRequest request = WebRequest.Create("http://pastebin.com/raw/Dtdf2qMp");
WebResponse response = request.GetResponse();
System.IO.StreamReader reader = new
System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
WebClient client = new WebClient();
client.DownloadFile (Link gotten from pastebin here, "c:\\File");
System.Threading.Thread.Sleep(5000);
Instead of dumping the text read to console output, you should assign it to a variable.
var pastebinOutput = reader.ReadToEnd();
Then just pass that as the link for the DownloadFile method. If you want to do verification that it's actually a URL you got from the original pastebin, you can look into System.Uri's TryCreate method.
I've got a solution - assuming you have your link in the raw pastebin link (mine is a .txt file saying 'it worked') I suggest you copy and paste the code below exactly - if you get an file saying 'it worked' then you can change the pastebin link & file names. If you don't want to open the file then remove Process.Start - if you want to change the delay just change the number (it's in milliseconds) Also, you can change the format from .txt to .exe or whatever your file is (or you can remove it so its the defualt name in the download link):
WebRequest request = WebRequest.Create("https://pastebin.com/raw/QAWufg1z");
WebResponse response = request.GetResponse();
System.IO.StreamReader reader = new
System.IO.StreamReader(response.GetResponseStream());
var pastebinOutput = reader.ReadToEnd();
WebClient client = new WebClient();
client.DownloadFile(pastebinOutput, #".\downloaded.txt");
MessageBox.Show("File should open automatically in the next minute. Please wait...");
await Task.Delay(3000); //3000 = 3 seconds
Process.Start(#".\downloaded.txt");
Im using visual studio 2008 and i want to convert .tiff file and show it to img. I can display the image using the url get from website. But when im using the path url from server it say that the parameter is not valid. I search all in the internet but cant find a solution that could fix it. Hope you could help me. Thanks in advance.
Heres my code.
string filename = "";
file_name = "https://support.leadtools.com/SupportPortal/CS/forums/44475/PostAttachment.aspx"; (This is the link i get from website. It successfully display the image)
// but when im using this to get the tiff it says parameter is not valid. The path i show below is just an example
filename = "http://123.456.7.89:00/test/test.tiff";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(file_name);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
Bitmap bm = new Bitmap(s);
I used to get this same kind of issue in my application once, in my case it was caused due to larger file size which wasn't properly loaded in memory at the time of accessing it. Please check the size of file you are trying to display.Hope this
helps.
I would like to load an excel file directly from an ftp site into a memory stream. Then I want to open the file in the FarPoint Spread control using the OpenExcel(Stream) method. My issue is I'm not sure if it's possible to download a file directly into memory. Anyone know if this is possible?
Yes, you can download a file from FTP to memory.
I think you can even pass the Stream from the FTP server to be processed by FarPoint.
WebRequest request = FtpWebRequest.Create("ftp://asd.com/file");
using (WebResponse response = request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
OpenExcel(responseStream);
}
Using WebClient you can do nearly the same. Generally using WebClient is easier but gives you less configuration options and control (eg.: No timeout setting).
WebClient wc = new WebClient();
using (MemoryStream stream = new MemoryStream(wc.DownloadData("ftp://asd.com/file")))
{
OpenExcel(stream);
}
Take a look at WebClient.DownloadData. You should be able to download the file directory to memory and not write it to a file first.
This is untested, but something like:
var spreadSheetStream
= new MemoryStream(new WebClient().DownloadData(yourFilePath));
I'm not familiar with FarPoint though, to say whether or not the stream can be used directly with the OpenExcel method. Online examples show the method being used with a FileStream, but I'd assume any kind of Stream would be accepted.
Download file from URL to memory.
My answer does not exactly show, how to download a file for use in Excel, but shows how to create a generic-purpose in-memory byte array.
private static byte[] DownloadFile(string url)
{
byte[] result = null;
using (WebClient webClient = new WebClient())
{
result = webClient.DownloadData(url);
}
return result;
}
I am using WebClient.DownloadFile to download a small executable file from the internet. This method is working very well. However, I would now like to download this executable file into a byte array rather than onto my hard drive. I did some reading and came across the WebClient.DownloadData method. The problem that I am having with the downloadData method is that rather than downloading my file, my code is downloading the HTML data behind my file's download page.
I have tried using dozens of sites - each brings me the same issue. Below is the code I am using.
// Create a new instance of the System.Net 'WebClient'
System.Net.WebClient client = new System.Net.WebClient();
// Download URL
Uri uri = new Uri("http://www35.multiupload.com:81/files/4D7B4D2BFC3F1A9F765A433BA32ED2C5883D0CE133154A0FDB7E7786547A3165DA62393141C4AF8FF36C75222566CF3EB64AF6FBCFC02099BB209C891529CF7B90C83D9C63D39D989CBB8ECE6DE2B83B/Project1.exe");
byte[] dbytes = client.DownloadData(uri);
MessageBox.Show(dbytes.Length.ToString()); // Not the size of my file
Keep in mind that I am attempting to download the data of an executable file into a byte array.
Thank you for any help,
Evan
You are attempting to download a file using an expired token url. See below:
URL: http://www35.multiupload.com:81/files/4D7B4D2BFC3F1A9F765A433BA32ED2C5883D0CE133154A0FDB7E7786547A3165DA62393141C4AF8FF36C75222566CF3EB64AF6FBCFC02099BB209C891529CF7B90C83D9C63D39D989CBB8ECE6DE2B83B/Project1.exe`
Server: www35
Token:
4D7B4D2BFC3F1A9F765A433BA32ED2C5883D0CE133154A0FDB7E7786547A3165DA62393141C4AF8FF36C75222566CF3EB64AF6FBCFC02099BB209C891529CF7B90C83D9C63D39D989CBB8ECE6DE2B83B
You can't just download a file by waiting for the timer to end, and copy the direct link, it's a "token" link. It will only work for a specified period of time before redirecting you back to the download page (which is why you are getting HTML instead of binary data).
Workaround
You will have to download the multiupload's HTML and parse the direct download link from the HTML source code. Only this way provides a sure-fire way of getting an up-to-date token url.
How #Dark Slipstream said, you're attempting to download a file using an expired token url
look how get the new url:
System.Net.WebClient client = new System.Net.WebClient();
// Download URL
Uri uri = new Uri("http://www.multiupload.com/39QMACX7XS");
byte[] dbytes = client.DownloadData(uri);
string responseStr = System.Text.Encoding.ASCII.GetString(dbytes);
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(responseStr);
string urlToDownload = doc.DocumentNode.SelectNodes("//a[contains(#href,'files/')]")[0].Attributes["href"].Value;
byte[] data = client.DownloadData(uri);
length = data.Length;
I dont parsing the exceptions
I have a sql table which holds information:
id (hash)
imagename string
width int
height int
What is the best way to create .net image read which will show images in page. I would like to call it like image.aspx/ashx?id=[id] and function will try to catch and show that image.
I know how to get data from SQL but I dont know how to read img from URL and show it as image.
Could any please point me at some relevant information how to do it or show piece of code how it works?
Do I read it as stream?
Thanks
string imageFileName = "thefile.jpg";
context.Request.MapPath(#"IMAGES\" + context.Request.QueryString["id"]);
context.Response.ContentType = "image/jpeg";
context.Response.WriteFile(imageFileName);
context.Response.Flush();
context.Response.Close();
http://blogs.msdn.com/b/alikl/archive/2008/05/02/asp-net-performance-sin-serving-images-dynamically-or-another-reason-to-love-fiddler.aspx
http://msdn.microsoft.com/en-us/library/ms973917.aspx
Check out this article: http://aspnet-cookbook.info/O.Reilly-ASP.NET.Cookbook.Second.Edition/0596100647/aspnetckbk2-CHP-20-SECT-2.html
You'll want to create an HttpHandler class and wire that up in your web.config.
You can retrieve remote resources (such as images) via HTTP using the System.Net.WebRequest class.
WebRequest request = WebRequest.Create("http://www.doesnotexist.com/ghost.png");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
BinaryReader reader = new BinaryReader(stream)
byte[] imageBytes = reader.ReadBytes(stream.Length);
Note that there might be better ways to read the bytes from the Stream. You should also remember to add using statements where appropriate to properly dispose of any unmanaged resources.