الأربعاء، 8 يونيو 2011

how to open,read and write to Files in C#


The Namespace

System.IO provides all the necessary classes, methods, and properties for manipulating directories and files. Table 1 elaborates the main classes under this namespace.

ClassPurpose/Use
Binary Reader and WriterRead and write primitive data types
Directory, File, DirectoryInfo, and FileInfoCreate, delete, and move files and directories. Get specific information about the files by making use of the properties defined in these classes.
FileStreamAccess the files in a random fashion
MemoryStreamAccess data stored in memory
StreamWriter and StreamReaderRead and write textual information
StringReader and StringWriterRead and write textual Information from a string buffer

Table 1—Classes under System.IO


Working with DirectoryInfo and FileInfo classes

The base class of DirectoryInfo and FileInfo is FileSystemInfo. This is an abstract class, meaning you can't instantiate this class. But you can use the properties defined by this class. Table 2 elaborates its properties and methods.
PropertiesPurpose/Use
AttributesReturns attributes associated with a file. Takes FileAttributes enumeration values
CreationTimeReturns the time of creation of the file
ExistsChecks whether a supplied file is a directory or not
ExtensionReturns the file extension
LastAccessTimeReturns last accessed time of the file
FullNameReturns the full path of the file
LastWriteTimeReturns the time of last written activity to the file
NameReturns the name of a given file
Delete()Deletes a file. Be careful when using this method.
Table 2—Members of FileSystemInfo class



Working with DirectoryInfo and FileInfo classes

The base class of DirectoryInfo and FileInfo is FileSystemInfo. This is an abstract class, meaning you can't instantiate this class. But you can use the properties defined by this class. Table 2 elaborates its properties and methods.
PropertiesPurpose/Use
AttributesReturns attributes associated with a file. Takes FileAttributes enumeration values
CreationTimeReturns the time of creation of the file
ExistsChecks whether a supplied file is a directory or not
ExtensionReturns the file extension
LastAccessTimeReturns last accessed time of the file
FullNameReturns the full path of the file
LastWriteTimeReturns the time of last written activity to the file
NameReturns the name of a given file
Delete()Deletes a file. Be careful when using this method.
Table 2—Members of FileSystemInfo class

The DirectoryInfo class provides methods for creating, moving, and deleting directories. To make use of the above properties, create an object of the DirectoryInfo class as shown in Listing 1:
Listing 1
DirectoryInfo dir1 = new DirectoryInfo(@"F:\WINNT");
You then can access the properties by using the object dir1, as shown in the code fragment in Listing 2:
Listing 2
Console.WriteLine("Full Name is : {0}", dir1.FullName);
Console.WriteLine("Attributes are : {0}",
                   dir1.Attributes.ToString());
You can also apply the values of FileAttributes enumeration. Its values are shown in Table 3.
PropertiesPurpose/Use
ArchiveReturns the file's Archive status
CompressedReturns whether the file is compressed or not
DirectoryReturns whether the file is a directory or not
EncryptedReturns whether the file is encrypted or not
HiddenReturns whether the file is hidden or not
OfflineSignifies that the data is not available
ReadOnlyIndicates that the file is read only
SystemIndicates that the file is a System file (probably a file under the Windows folder)
Table 3—FileAttributes Enumeration Values

Working with Files under a Directory

Suppose that you want to list all BMP files under the f:\Pictures directory. You can write a code as shown in the code snippet given in Listing 3:
Listing 3
DirectoryInfo dir = new DirectoryInfo(@"F:\WINNT");
FileInfo[] bmpfiles = dir.GetFiles("*.bmp);
Console.WriteLine("Total number of bmp files", bmpfiles.Length);
Foreach( FileInfo f in bmpfiles)
{
  Console.WriteLine("Name is : {0}", f.Name);
  Console.WriteLine("Length of the file is : {0}", f.Length);
  Console.WriteLine("Creation time is : {0}", f.CreationTime);
  Console.WriteLine("Attributes of the file are : {0}",
                     f.Attributes.ToString());
}

Creating Subdirectories

You can easily create a subdirectory. Listing fragment 4 describes how to create a subdirectory called MySub under the Sub directory.
Listing 4
DirectoryInfo dir = new DirectoryInfo(@"F:\WINNT");
try
{
  dir.CreateSubdirectory("Sub");
  dir.CreateSubdirectory(@"Sub\MySub");
}
catch(IOException e) 
{
  Console.WriteLine(e.Message);
}

Creating Files by Using the FileInfo Class

With the FileInfo class, you can create new files, access information about the files, delete, and move files. This class also provides methods for opening, reading from, and writing to a file. Listing 5 shows how to create a text file and access its information like its creation time, full name, and so forth.
Listing 5
FileInfo fi = new FileInfo(@"F:\Myprogram.txt");
FileStream fstr = fi.Create();
Console.WriteLine("Creation Time: {0}",f.CreationTime);
Console.WriteLine("Full Name: {0}",f.FullName);
Console.WriteLine("FileAttributes: {0}",f.Attributes.ToString());

//Way to delete Myprogram.txt file.

Console.WriteLine("Press any key to delete the file");
Console.Read();
fstr.Close();
fi.Delete();

Understanding the Open() Method

The FileInfo class defines a method named Open() with which you can create files by applying the values of the FileMode and FileAccess enumerations. The code snippet in Listing 6 describes its usage:
Listing 6
FileInfo f = new FileInfo("c:\myfile.txt");
FileStream s = f.Open(FileMode.OpenorWrite, FileAccess.Read);
You then can read from and write to a file by using the object 's'. In the overloaded Open() method, permission is given only for reading from a file. If you want to write to a file, you have to apply the ReadWrite value of FileAccess enumeration. Tables 4 and 5 describe the values of the FileMode and FileAccess enumerations.
ValuesPurpose/Use
AppendOpens the file and adds data. This should be used with the FileAccess Write Enumeration value.
CreateCreates a new file. Overwrites any existing file.
CreateNewCreates a new file. If the file already exists, IOException is thrown.
OpenOpens an existing file
OpenOrCreateOpens a new file. If there is no file, it creates a new file.
TruncateTruncates an existing file
Table 4—FileMode Enumeration values
ValuesPurpose/Use
ReadData can be read (retrieved) from the file
ReadWriteData can be added to and retrieved from the file
WriteData can be added to the file
Table 5—FileAccess Enumeration values

Writing to a Text File by Using the StreamWriter Class

You can easily write texts or other information to a file by using the CreateText() method of the FileInfo class. However, you have to obtain a valid StreamWriter. It's this StreamWriter reference that provides the required functionalities for writing to a file. To illustrate, Listing 7 writes a series of texts to the Mytext.txt file.
Listing 7
FileInfo f = new FileInfo("Mytext.txt")
StreamWriter w = f.CreateText();
w.WriteLine("This is from");
w.WriteLine("Chapter 6");
w.WriteLine("Of C# Module");
w.Write(w.NewLine);
w.WriteLine("Thanks for your time");
w.Close();

Reading from a Text File

You can read from a Text file by using the StreamReader class. For this, you have to specify the file name using the static OpenText() method of the File class. Listing 8 reads the contents that we have written in Listing 7:
Listing 8
Console.WriteLine("Reading the contents from the file");
StreamReader s = File.OpenText("Mytext.txt");
string read = null;
while ((read = s.ReadLine()) != null)
{
  Console.WriteLine(read);
}
s.Close();

ليست هناك تعليقات:

إرسال تعليق