Friday, September 17, 2010

Copy complete folder with respective folder hierarchy to another location

public class FileSystem{
// Copy directory structure recursively

public static void copyDirectory(string Src,string Dst){
String[] Files;

if(Dst[Dst.Length-1]!=Path.DirectorySeparatorChar)
Dst+=Path.DirectorySeparatorChar;
if(!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
Files=Directory.GetFileSystemEntries(Src);
foreach(string Element in Files){
// Sub directories

if(Directory.Exists(Element))
copyDirectory(Element,Dst+Path.GetFileName(Element));
// Files in directory

else
File.Copy(Element,Dst+Path.GetFileName(Element),true);
}
}

}

Thursday, September 2, 2010

How to write XML File from the Object Collection

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class WriteProductXMLFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
WriteProducts("9955");
}
}

public System.Collections.IEnumerable CreateProducts()
{
List products = new List();


products.Add(Product.Create("1", "AAAA"));
products.Add(Product.Create("2", "BBBB"));
products.Add(Product.Create("3", "JJJJJ"));
products.Add(Product.Create("4", "AAAKKKA"));
products.Add(Product.Create("5", "YYYYY"));
products.Add(Product.Create("6", "PPPPP"));
products.Add(Product.Create("7", "MMMMM"));
products.Add(Product.Create("8", "TTTTT"));


return products;

}


protected void WriteProducts(string CustomerID)
{

System.Collections.IEnumerable products = CreateProducts();

string FileName = "Products_" + CustomerID+".xml";

string FilePath = Server.MapPath(FileName);

if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
}

XmlTextWriter XmlWriter = new XmlTextWriter(FilePath, null);

XmlWriter.WriteStartDocument();
XmlWriter.WriteComment("Product XML.");
XmlWriter.WriteStartElement("Products of Customer: ID");

foreach (Product prod in products)
{

XmlWriter.WriteStartElement("Product");
XmlWriter.WriteElementString("ProductID", prod.ProductID);
XmlWriter.WriteElementString("ProductImage", prod.ProductImage);
XmlWriter.WriteEndElement();
}


XmlWriter.WriteEndDocument();
XmlWriter.Flush();
XmlWriter.Close();

}


# region Internal Class


public class Product
{
public static Product Create(string productID,
string productImage)
{
Product product = new Product();

product.ProductID = productID;
product.ProductImage = productImage;

return product;
}

private string _productID;

public string ProductID
{
get { return _productID; }
set { _productID = value; }
}

private string _Image;
public string ProductImage
{
get { return _Image; }
set { _Image = value; }
}

}

#endregion



}
 
Locations of visitors to this page