Pages

Monday, May 20, 2013

How to download a file from Web Server using ASP.NET

To Download a file from Web Server you can use the TransmitFile method of HttpResponse class. This function writes the file to an HTTP response output stream without buffering it in memory, see the example below,
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename="+strFileName);
Response.TransmitFile(Server.MapPath("~/FileUpload/" + strFileName));
Response.End();
In the above example, downloading the file as an attachment. 

How to add a new row of record to an XML file in ASP.NET

See the example first,
 XmlDocument xmldoc = new XmlDocument();
 xmldoc.Load(Server.MapPath("Users.xml"));
 XmlElement parentelement = xmldoc.CreateElement("users");
 XmlElement uname = xmldoc.CreateElement("UserName");
 XmlElement password = xmldoc.CreateElement("Password");
 XmlElement role = xmldoc.CreateElement("Role");
 uname.InnerText = txtUsrname.Text.Trim();
 password.InnerText = txtPass.Text.Trim();
 role.InnerText = txtRole.Text.Trim();
 parentelement.AppendChild(uname);
 parentelement.AppendChild(password);
 parentelement.AppendChild(role);
 xmldoc.DocumentElement.AppendChild(parentelement);
 xmldoc.Save(Server.MapPath("Users.xml"));
 lblresult.ForeColor = System.Drawing.Color.Green;
 lblresult.Text = " User "+txtUsrname.Text.Trim() + " added successfully";
 BindData();
The above example, XML file is using to keep authentication users list, it has three fields such as User Name, Password and Role. The above code add a new user to the XML file and shows the message. 

How to SELECT a specific row of data from a Data Table using a condition in ASP.NET

To retrieve a Data Row as per a filter condition you can use the SELECT method of Data Table. The SELECT method returns an array of all DataRow that match the filter condition. The SELECT method returns DataRow object. For Example,


var user = Users.Select("UserName='" + txtUsrname.Text.Trim() + "'");
The above example, "Users" is the Data Table, and trying to get the specific user as per your input on txtUsrname text field. For instance, if you want to check a particular user is already exist or not, first load all the users to a Data Table and filter the users table using the SELECT method, and check the array length using "if" condition. For example

DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Users.xml"));
DataTable Users = DS.Tables[0];
var user = Users.Select("UserName='" + txtUsrname.Text.Trim() + "'");
if (user.Length != 0)
{
 lblresult.ForeColor = System.Drawing.Color.Red;
 lblresult.Text = "User "+txtUsrname.Text + " Already exist";
 return;
}