Sunday, March 21, 2010

File Download in ASP.Net with C#


The following code can be used for downloading files in our application.The Original path of the file will be hidden using this code.
private void btnDownload_Click(object sender, System.EventArgs e)
{
// The file path to download.
string filepath = @"C:\shadow_copy.rar";
// The file name used to save the file to the client's system..
string filename = Path.GetFileName( filepath );
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream( filepath, System.IO.FileMode.Open,System.IO.FileAccess.Read, System.IO.FileShare.Read );
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader( "Content-Disposition", "attachment; filename=" + filename );
// Read the bytes from the stream in small portions.
while ( bytesToRead > 0 )
{
// Make sure the client is still connected.
if ( Response.IsClientConnected )
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read( buffer, 0, 10000 );
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if ( stream != null ) {
stream.Close();
}
}
}

How to retrieve and create cookies?

ASP is very powerful while managing cookies. It's so easy to create a cookie. You may use response object and cookie property to create it. Again request object used to retrieve cookie. Cookies must be written before header sent to client by server. This means you should write and send cookie befre any HTML opening tag.
Example:
Create cookie:
strCookieName =  "Acookie"
strCookieValue =  "I am a cookie"
'let's create it now
response.cookie(strCookieName) = strCookieValue
Retrive value from cookie
strValueFromCookie = request.cookie(strCookieName)
 
That's all. A cookie dies noamlly after closing browser. You may edit a cookie lifetime by passing a value to expires property.
Response.Cookies(strCookieName).Expires=date()+10
This cookie will be avalaible for 10 days.
How to create a cookie.

Here's a new cookie named cakes.
HttpCookie myCookie = new HttpCookie("cakes");


We created the cookie but there are no keys with values in it, so for now it's useless. So let's add some:






myCookie.Values.Add("muffin", "chocolate");

myCookie.Values.Add("babka", "cinnamon");



We also need to add the cookie to the cookie collection (consider it a cookie jar ):





Response.Cookies.Add(myCookie);



How to get the value stored in a cookie.

Here's how to get the keys and values stored in a cookie:





Response.Write(myCookie.Value.ToString());



The output to using this with the previous created cookie is this: "muffin=chocolate&babka=cinnamon".



However, most of the time you'll want to get the value stored at a specific key. If we want to find the value stored at our babka key, we use this:






Response.Write(myCookie["babka"].ToString());



Set the lifetime for a cookie.

You can easily set the time when a cookie expires. We'll set the Expires property of myCookie to the current time + 12 hours:







myCookie.Expires = DateTime.Now.AddHours(12);



This cookie will expire in twelve hours starting now. You could as well make it expire after a week:






myCookie.Expires = DateTime.Now.AddDays(7);



Also note that if you don't set a cookie's expiration date & time a transient cookie will be created - a cookie which only exists in the current browser instance. So if you want the cookie to be stored as a file you need to set this property.


Setting the cookie's path.

Sometimes you'll want to set a path for a cookie so that it will be available only for that path in your website (ex.: www.geekpedia.com/forums). You can set a cookie's path with the Path property:






myCookie.Path = "/forums";



Setting the domain for a cookie.

Perhaps instead of using http://www.geekpedia.com/forums path style to your forums, you would use a subdomain like http://forums.geekpedia.com. The Domain property should do it:





myCookie.Domain = "forums.geekpedia.com";



How to edit a cookie.

You don't actually edit a cookie, you simply overwrite it by creating a new cookie with the same key(s).



How to destroy / delete a cookie.

There's no method called Delete which deletes the cookie you want. What you can do if you have to get rid of a cookie is to set its expiration date to a date that has already passed, for example a day earlier. This way the browser will destroy it.





myCookie.Expires = DateTime.Now.AddDays(-1);



How to remove a subkey from a cookie.

This is one of the problems I encountered with cookies. Fortunately I found an answer on MSDN. You can use the Remove method:





myCookie.Values.Remove("babka");



However, you don't usually remove a subkey immediatly after creating it, so first we need to retrieve the cookie, remove the subkey and then add it back to the Cookies collection:





// Get the cookie from the collection (jar)

myCookie = Request.Cookies["cakes"];

// Remove the key 'babka'

myCookie.Values.Remove("babka");

// Add the cookie back to the collection (jar)

Response.Cookies.Add(myCookie);

// See what's in the cookie now

Response.Write(myCookie.Values.ToString());



Of course I suppose you used the code we created earlier (the one with the chocolate muffin and the cinnamon babka), therefore if you test the code now you'll see the result is 'muffin=chocolate' - we got rid of the babka!