Introduction
This article consists of operations which will transfer data to an XML file and read data from an XML file.
The method
First, create a simple ASPX page and name it as XML. Add a file, DataList, UploadButton inside the DataList tag. Add an img tag and set the image URL to:
Imgurl =<%#" content.aspx?id="+DataBinder.Eval(container.DataItem,"id") %>
Code
try
{
DataSet ds=new DataSet();
ds.ReadXml(Server.MapPath("XMLFile1.xml"));
DataList1.DataSource=ds;
DataList1.DataBind();
}
catch (Exception ex){Response.Write(ex.Message);}
private void Button1_ServerClick(object sender, System.EventArgs e)
{
Int64 len=file1.PostedFile.ContentLength;
Byte[] byt=new byte[len];
Stream st=file1.PostedFile.InputStream;
int n = st.Read(byt,0,(int)len);
DataSet ds=new DataSet();
ds.ReadXml(Server.MapPath("XMLFile1.xml"));
DataRow dr=ds.Tables[0].NewRow();
dr["id"]=TextBox1.Text;
dr["data"]=Implode(byt);
ds.Tables[0].Rows.Add(dr);
ds.WriteXml(Server.MapPath("XMLFile1.xml"));
bind();
}
public string Implode(Byte[] array)
{
String data=String.Empty;
for (int i = 0; i < array.Length; ++i)
data+=array[i].ToString()+"#";
return data;
}
In the class file, read the XML file and store it in a DataSet, fill the data source of the DataList with the DataSet, and bind it.
Create another page: content.aspx
In the class file, get the request for the ID and check for the ID in the XML. If found, fill the data tag file to a string array and transfer it to bytes. Then, provide the response to the request by providing the content type and binary data.
string id=Request.QueryString["id"].ToString();
DataSet ds = new Dataset()
ds.ReadXml(Server.MapPath("XMLFile1.xml"));
{
id=Request.QueryString["id"].ToString();
foreach (DataRow dr in ds.Tables[0].Rows)
if(dr["id"].ToString()==id)
try
{
string[] str=dr["data"].ToString().Split('#');
for (Int64 i = 0; i < str.Length-1; i++)
byt[i]=Convert.ToByte(str[i].ToString());
break;
Byte[] byt=new byte[str.Length];
byt[i]=Convert.ToByte(str[i].ToString());
Context.Response.ContentType="image/";
Context.Response.BinaryWrite((byte[])byt);
}
catch(Exception ex){Console.Write(ex);}
}
Upload new data
To upload new data, browse the file and stream it. Later, store it to the XML file by converting the bytes[] and save the DataSet.
Finally
If you have a simpler solution than this, don't fail to email me about it.