Monday, December 29, 2008

Execl to Folder ceation in file handling

Hi Gagan,
In this post I will explain how to create folder if we we have already name of folder in our Excel file.
Here I have Excel

I need to create folder as mentioned in its first column

In C#.net we need to create Oledb connectioon to access data from Excel.
I have given Sample code you can understand easily by it

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.OleDb;

using System.IO;

namespace xlsToFolder

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"D:\c3.xls" + ";Extended Properties=Excel 8.0");

con.Open();

try

{

DataSet myDataSet = new DataSet();

OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM [" + "Sheet1" + "$]", con);

myCommand.Fill(myDataSet);

con.Close();

//MessageBox.Show(myCommand.ToString());

// textBox1.AppendText("\nDataSet Filled");

//Travers through each row in the dataset

foreach (DataRow myDataRow in myDataSet.Tables[0].Rows)

{

//Stores info in Datarow into an array

Object[] cells = myDataRow.ItemArray;

//Traverse through each array and put into object cellContent as type Object

//Using Object as for some reason the Dataset reads some blank value which

//causes a hissy fit when trying to read. By using object I can convert to

//String at a later point.

foreach (object cellContent in cells)

{

//Convert object cellContect into String to read whilst replacing Line Breaks with a defined character

string cellText = cellContent.ToString();


//It will create the folder under folder named Test4 System.IO.Directory.CreateDirectory("c:/Test4/" + cellText);

}

}

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

finally

{

con.Close();

}

}

}

}






Read XML in C#.net

We can use File object to read XML file but we mostly use XML parsing.

.NET provides five namespace to support XML classes.
  1. System.Xml;
  2. .Xml.Schema;
  3. .Xml.Serialization;
  4. .Xml.XPath;
  5. .Xml.Xsl;
The System.Xml namespace contains major XML classes.

The XmlReader class is an abstract bases classes and contains methods and properties to read a document.
The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas.
The XmlWrite class contains functionality to write data to XML documents.
XmlNode class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes. The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively.

Reading XML Documents

XmlTextReader xmlReader = new XmlTextReader("D:\\test.xml");

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor.

XmlTextReader xmlReader = new XmlTextReader("D:\\test.xml");

Then call read() method

xmlReader.read();


using System;

using System.Xml;

namespace ReadXml

{

class Class1

{

static void Main(string[] args)

{

// Create an isntance of XmlXmlReader and call Read method to read the file

XmlXmlReader xmlReader = new XmlXmlReader("D:\\test.xml");

xmlReader.Read();

// If the node has value

while (xmlReader.Read())

{

// Move to fist element

xmlReader.MoveToElement();

Console.WriteLine("XmlXmlReader Properties Test");

Console.WriteLine("===================");

// Read this element's properties and display them

Console.WriteLine("Name:" + xmlReader.Name);

Console.WriteLine("Base URI:" + xmlReader.BaseURI);

Console.WriteLine("Local Name:" + xmlReader.LocalName);

Console.WriteLine("Attribute Count:" + xmlReader.AttributeCount.ToString());

Console.WriteLine("Depth:" + xmlReader.Depth.ToString());

Console.WriteLine("Line Number:" + xmlReader.LineNumber.ToString());

Console.WriteLine("Node Type:" + xmlReader.NodeType.ToString());

Console.WriteLine("Attribute Count:" + xmlReader.Value.ToString());

}

}

}

}




Writing XML Documents

XmlTextWriter textWriter = new XmlTextWriter("D:\\testWrite.xml", null) ;



using System;

using System.Xml;

namespace ReadingXML2

{

class Class1

{

static void Main(string[] args)

{

// Create a new file in C:\\ dir

XmlTextWriter textWriter = new XmlTextWriter("D:\\testWrite.xml", null);

// Opens the document

textWriter.WriteStartDocument();

// Write comments

textWriter.WriteComment("First Comment XmlTextWriter Sample Example");

textWriter.WriteComment("myXmlFile.xml in root dir");

// Write first element

textWriter.WriteStartElement("Student");

textWriter.WriteStartElement("r", "RECORD", "urn:record");

// Write next element

textWriter.WriteStartElement("Name", "");

textWriter.WriteString("Student");

textWriter.WriteEndElement();

// Write one more element

textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");

textWriter.WriteEndElement();

// WriteChars

char[] ch = new char[3];

ch[0] = 'a';

ch[1] = 'r';

ch[2] = 'c';

textWriter.WriteStartElement("Char");

textWriter.WriteChars(ch, 0, ch.Length);

textWriter.WriteEndElement();

// Ends the document.

textWriter.WriteEndDocument();

// close writer

textWriter.Close();

}

}

}




Sunday, December 28, 2008

File Handling In C#

File is a static class.

The table shows the most useful File methods we can use.

Method name

Use

File.ReadAllBytes

Useful for files not stored as plain text.
See example near the bottom.

File.ReadAllLines

Microsoft: "Opens a file, reads all lines of the file with the specified encoding, and closes the file."
See the benchmark below.

File.ReadAllText

Returns the contents of the text file at the specified path as a string.
See the benchmark below.

File.WriteAllBytes

Not covered here.
It should be used in conjunction with File.ReadAllBytes.

File.WriteAllLines

Stores a string array in the specified file, overwriting the contents.

File.WriteAllText

Writes the contents string to a text file.

File.AppendAllText

Use to append the contents string to the file at path.
Microsoft: "Appends the specified string to the file, creating the file if it doesn't already exist."

File.AppendText

Not covered here.
You must use standard StreamWriter code.




File.ReadAllBytes.

we can use it to cache an image in memory for performance.It will increase the performance too.


static class ImageCache
{
static byte[] _logoBytes;
public static byte[] Logo
{
get
{
//
// Returns logo image bytes.
//


if (_logoBytes == null)
{
_logoBytes = File.ReadAllBytes("Logo.png");
}
return _logoBytes;
}
}
}


File.ReadAllLines

The following code reads in each line in the file "file.txt" into an array.


// Read in every line in specified file.
// This will store all lines in an array in memory,
// which you may not want or need.
//

string[] lines = File.ReadAllLines("file.txt");
foreach (string line in lines)
{
//
// Do something with line
//

if (line.Length > 80)
{
// Example code (disregard).
}
}


StreamReader ReadLine

This method is not part of the File static class, but it is in the System.IO
namespace. I provide it here as a comparison to the File.ReadAllLines method.
Here is some data about how the two methods to read lines perform on different
sized files.



// Read in every line in the file.
//
// Note how |using| wraps the StreamReader.
// The condition in |while| is also very important to get right.
//

using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
//
// Do something with line just for example.
//

string[] parts = line.Split(',');
}
}


File.ReadAllText

It is used to rad the text from our data file.


void Example()
{
//
// A.
// Read in file with File class.
//
string text1 = File.ReadAllText("file.txt");

//
// B.
// Read in file text with helper method and StreamReader.
// 40% faster!
//
string text2 = ReadFileString("file.txt");
}

static string ReadFileString(string path)
{
//
// Use StreamReader to consume the entire text file.
//
using (StreamReader reader = new StreamReader(path))
{
return reader.ReadToEnd();
}
}

StreamReader helper. In some projects, it would be worthwhile to use the above ReadFileString custom static method.


File.ReadAllLines

List and ArrayList are extremely useful data structures for us programmers, as they allow us to rapidly expand (or shrink) large (or small) 'collections' of objects. Here we see how we can use LINQ to get a List of lines from a file in one line.



//
// Read in all lines in the file,
// and then convert to List with LINQ.
//
List fileLines = File.ReadAllLines("file.txt").ToList();



File.ReadAllLines

Do you need to count the lines in a file? Every developer has had this requirement at some time. Are there 10 or 10,000 lines in the web server log file? We don't need to write ten lines of code to do this. Simply reference the Length property.


// Another method of counting lines in a file.
// This is NOT the most efficient way, and it
// counts empty lines.
//
int lineCount = File.ReadAllLines("file.txt").Length;

See if a line exists in a file

Does a line containing a specific string exist in the file? Maybe you want to see if a name or location exists in a line in the file. Here again we can harness the power of LINQ to find any matching line.


// One way to see if a certain string is a line
// in the specified file. Uses LINQ to count elements
// (matching lines), and then sets |exists| to true
// if more than 0 matches were found.
//
bool exists = (from line in File.ReadAllLines("file.txt")
where line == "Some line match"
select line).Count() > 0;



File.WriteAllLines

When you are done with your in-memory processing, you often need to write the data to disk. Fortunately, the File class offers an excellent WriteAllLines method. It receives the file path and then the array to write. This will replace all the file contents.


// Write a string array to a file.

string[] stringArray = new string[]
{
"cat",
"dog",
"arrow"
};
File.WriteAllLines("file.txt", stringArray);
// File contains:
// cat
// dog
// arrow


Append text to files

The previous example will replace the file's contents, but for a log file or error listing, we must append to the file. (Sure, we could read in the file, append to that in memory, and then write it out completely again. But that's slow.)


// Append text to a file.
// This method will create a new file if one isn't already there.
// No newlines will be automatically added.
//
File.AppendAllText("file.txt", "test");
// File contains:
// test
File.AppendAllText("file.txt", "more");
// File contains:
// testmore
So friends File handling is quite easy in C#.

Saturday, December 27, 2008

How to Delete Folder/File on System with C#

File handling:

In any software application we need to do some following tasks:

  • Create new Folder/File.
  • Edit Folder/File.
  • Delete Folder/File

For above type of work in our application we need to use File handling.
Generally we get all examples related to create and edit in lot of websites.
But How to delete the
Folder/File It is not common So I am taking the example how to delete the Directory/File in C#.


Namespace: System.IO

Assembly: mscorlib (in mscorlib.dll)


This Programs is made for console application



//By: Raman

//Purpose: To delete the particular folder in your system

//Code Start

using System.IO;

class deleteFolder

{

protected void delFolder()

{

//delete folder has been created in E:\ drive you can make your any named folder

//Lets assume we have junk images stored in that folder

DirectoryInfo imgInfo = new DirectoryInfo(@"E:\delete");

FileInfo []fileinDir=imgInfo.GetFiles();

for(int i=0;i

{

fileinDir[i].Delete();

}

//delete method will delete the current file

imgInfo.Delete();

}

public static void Main()

{

deleteFolder obj=new deleteFolder ();

obj. delFolder ();

}

}

//Code End



Any Query on file handling would be appreciated


* This program is used to delete the particular folder on your window. It could be destructive so please use it carefully