Monday, February 15, 2010

File and Directory related class, method and operation.

1) StreamWriter class under System.IO namespace
Example: - using(StreamWriter swInstance = new StreamWriter(“FileName.txt”))
{… ..}
2) StreamWriter.Write() method
3) StreamWriter.WriteLine() method
4) File.CreateText() operation
5) File.AppendText() operation
6) StreamReader class
Example: - using(StreamReader readMe = new StreamReader(“FileName.txt”))
{… ..}
7) StreamReader.ReadLine() mehod: - This is the key method to read the contents of a text file. Text is treated as chunks of data demarcated by line breaks. More specifically, the line breaks are either a carriage return (“\r”) or line feed (“\n”), or a combination of carriage return and by a line feed (“\r\n”).
8) DirectoryInfo class: - using DirectoryInfo class, we can create, move, and display directories in addition to viewing files. For the purpose of reading text files, all we need to do is to find the directory with our files. There are two method under DirectoryInfo class first is DirectoryInfo.FetDirectories() and second is DirectoryInfo.GetFiles().
• Locating and Displaying Directories: - In using the DirectoryInfo class, an instance is created using a starting point in the directory structure. For example, the following shows the format for the root C: directory:
DirectoryInfo dir = new DirectoryInfo(@”C:\\”);

To view the directories at the C: root, you can iterate through the DirectoryInfo instance to pull out the full set of directories using the following format:

Foreach(DirectoryInfo dirInfoInstance in dirInfo.GetDirectories()) … .

• Locating and Displaying Files: - If we use files for storing different kinds of data, sometimes we might forget the location of the file or its name. Using the DirectoryInfo.GetFiles() method, we can retrieve the filenames in a given directory. The FileInfo class is similar to the DirectoryInfo class, except it is used with files rather than directories. However, we can work with both to locate a file within a directory. When iterating through a DirectoryInfo object, instead of using a DirectoryInfo instance to locate a specific directory, you use a FileInfo object as the element to retrieve the files in the directory. The format
Foreach(FileInfo fileInfo in directoryInfoInstance.GetFiles())
Finds the files in the specified instance of the DirectoryInfo method GetFiles().


When we enter data into a text file using the WriteLine() method, it automatically enters a line break, so when you use the ReadLine(), it knows what text is considered to be a separate line. Text entered in other ways marks the end of the line with either of the other two acceptable markers that ReadLine() can find.

No comments:

Post a Comment