Introduction
Did you ever get such a requirement to create the shortcut of your website with query string? Also, user should be able to create the shortcut of website from the page itself. User just needs one button click to have his/her shortcut URL ready on his/her desktop.
It is very easy to create the shortcut through Microsoft's built in utility. At the same time, it is somewhat tricky to create the shortcut of your URL through your website only. As you know, you can't create a shortcut on Client's machine due to security concerns through any web page.
In this article, I will show you how to create a shortcut file and save/download it using Jquery. I have tried my best to provide clean code with comments.
Using the Code
- Create one empty website.
- Add default page.
- Add the below jquery files:
- jquery-1.7.1.min
- json2-min
HTML Code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="js/json2-min.js"></script>
<script src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function GenerateShortCut() {
var params = new Object();
params.url = '<%= Request.Url %>';
$.ajax
({
url: "Default.aspx/GenerateShortCut",
data: JSON.stringify(params), dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () { document.getElementById('<%= btnDownload.ClientID %>').click(); },
failure: function () { }
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="Create Shortcut" onclick="GenerateShortCut();" />
<div style="display:none">
<asp:Button ID="btnDownload" runat="server" />
</div>
</div>
</form>
</body>
</html>
Default.cs
using System;
using System.IO;
using System.Web;
using System.Web.Services;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnDownload.Click += btnDownload_Click;
}
void btnDownload_Click(object sender, EventArgs e)
{
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment; filename=test.url"); HttpContext.Current.Response.TransmitFile
(HttpContext.Current.Server.MapPath("~/Temp/test.url")); HttpContext.Current.Response.End();
}
[WebMethod]
public static string GenerateShortCut(string url)
{
try
{
string[] lines = { "[InternetShortcut]", "URL=" + url,
"IconFile=", "IconIndex=0" };
if (File.Exists(HttpContext.Current.Server.MapPath("").ToString() +
"\\temp\\test.url")) {
File.Delete(HttpContext.Current.Server.MapPath("").ToString() +
"\\temp\\test.url"); }
using (System.IO.StreamWriter file = new System.IO.StreamWriter
((HttpContext.Current.Server.MapPath("").ToString() +
"\\Temp\\test.url"))) {
foreach (string line in lines)
{
file.WriteLine(line);
}
}
}
catch (Exception ex)
{
}
return "";
}
}