TURKISH BLOG   |  ABOUT ME  |  ARCHIVES  | DELETE LANGUAGE COOKIE

Enes TAYLAN

Mind Hegemony - Mood 1.0 - Total Control Edition

.NET IO - 2 ( Reading from and Writing to Files )

clock June 19, 2009 21:16
We are continuing from where we left in System.IO. (for the first article click) In .NET IO to write or read, we should use a stream or specific stream classes that extends abstract base class Stream. For example:

  • System.IO.FileStream
  • System.IO.MemoryStream
  • System.Net.Sockets.NetworkStream
  • System.IO.BufferedStream
In this article I'll use System.IO.FileStream to read from and write to a file. Let's look at this code:
 FileStream fs = new FileStream(Server.MapPath("example.txt"), FileMode.Open);
 //By using FileStream, we start to read the file. "FileMode.Open" means that this
 //file will be used just for reading not another operations. Other possible values are:
 //Append,Create,Truncate,CreateNew,OpenOrCreate 

byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length);
//we read the whole file by "from 0 to fs.length" 

foreach (byte k in data) 
{ 
    Response.Write(k.ToString()); 
} 
//and we send the result to the user 
When we run this example, we can get some meaningless results. The reason is "FileStream" gives us the result as "byte". If we don't want to transform these bytes to human-readable form, we should use "System.IO.StreamWriter" and "System.IO.StreamReader".
StreamWriter writer = new StreamWriter(File.Open(Server.MapPath("enes.txt"), FileMode.Open)); 
//file.open() -->> creates a filestream for streamwriter 
writer.Write("write to the file");
writer.Close(); 

////////////////////////////////////////////////////////// 

StreamReader reader = new StreamReader(File.Open(Server.MapPath("enes.txt"), FileMode.Open));
Label1.Text = reader.ReadLine(); 
reader.Close(); 
"System.IO.StreamWriter" and "System.IO.StreamReader" creates "System.IO.FileStream" themselves (so we don't need to create them)  "Label1.Text = reader.ReadLine(); " enables us to read file line by line. If we wanted to read whole file as a single chunk, we would write  "Label1.Text = reader.ReadToEnd(); " Besides these methods there are other static methods in System.IO that allows us carry out these operations easier:
 string k = File.ReadAllText(Server.MapPath("enes.txt")); 
and
 File.WriteAllText(@"C:\temp.txt",data); 


.NET IO - 1 ( Creating and Deleting Files and Directories and Listing subfiles and subdirectories )

clock June 10, 2009 07:13
There are advanced classes in .NET for IO processing. Even though we have some classes that allow us to carry out low level IO operations, we can usually do our work with several static methods. Now let's see how a directory and a file is created, deleted and how directory hierarchy in a disk volume or in a directory can be displayed in tree view. Although IO operations are same in all .NET projects, to make easier our article I use ASP.NET. Hence you can easily copy and paste code below in, for example, WPF. Classes, we will use, are:

  • DriveInfo
  • DirectoryInfo
  • FileInfo
  • Directory
  • File
To create a directory or file
Directory and File classes in System.IO namespace allow us to create and delete directories or files:
Directory.Create(@"C:\exampleDirectory");
Directory.Delete(@"C:\exampleDirectory");
If we want to work on files and directories in current project folder, 
Directory.Create(@"Server.MapPath("exampleDirectory"));  
Directory.Delete(@"Server.MapPath("exampleDirectory"));  
we can use. When operating on files, use File class:
File.Create(@"C:\exampleFile.doc")
File.Delete(@"C:\exampleFile.doc")
or
File.Create(@"Server.MapPath("exampleFile"));  
File.Delete(@"Server.MapPath("exampleFile"));  
Now let's work on displaying directory and file hierarchy in treeView like "windows explorer" style. We will use these classes:

  • System.IO.DriveInfo        //allows us to access the name, available space, total space etc. of a disk volume
  • System.IO.DirectoryInfo    //allows us to access the name, available space, total space etc. of directory
Create a new site, add TreeView and wrote below code in Page_Load event:
rotected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            System.IO.DriveInfo drive = new System.IO.DriveInfo(@"D:\"); 
            //work on local disk D
            TreeNode node = new TreeNode(); 
            //we create TreeNode's dinamically

            node.Value = drive.Name;  
            TreeView1.Nodes.Add(node); 
            //add local disk D to main node

            loadDirectories (node, drive.Name);//in this recursive method,
            // we pass name and full address of the local disk 
            // as parameters            
        }
    }

    private void loadDirectories(TreeNode parent, string path)
    {
        System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(path); 
        //now we don't work on drives but directories

        try
        {
           //with  GetDirectories(), we get all sub directories
            foreach (System.IO.DirectoryInfo d in directory.GetDirectories()) 
            {
                TreeNode node = new TreeNode(d.Name, d.FullName);                

                parent.ChildNodes.Add(node);  

                //call the same method (call "loadDirectories()" recursively )
                loadDirectories(node, d.FullName);        
            }
        }
        catch (System.UnauthorizedAccessException e)
        {
            parent.Text += "(acces forbiddeni)";
        }

        catch (System.IO.IOException e)
        {
            parent.Text += "(unknown error hata: " + e.Message + ")";
        }   
    }
We displayed just content of volume D by writing ?System.IO.DriveInfo drive = new System.IO.DriveInfo(@"D:\");". If we wanted to display all files and directories in computer hard disk, we would write:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            foreach (System.IO.DriveInfo drive in System.IO.DriveInfo.GetDrives())  
            //to work on all volumes
            {
                TreeNode node = new TreeNode();
                node.Value = drive.Name;

                if (drive.IsReady)
                {
                    node.Text = drive.Name;
                    loadDirectories(node, drive.Name);
                }                            

                TreeView1.Nodes.Add(node);
            } 
        }
}
The code below takes several minutes. As you can estimate,  our recursive method "loadDirectories()" needs many IO operations.

Now add a GridView to the project. We want to select a file from the TreeView we just created, and see alll subfiles and subdirectories with their name, space, last access time etc. Select SelectedNodeChanged event in "Properties Window" after clicking on TreeView and write the code below.
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        DirectoryInfo directory = new DirectoryInfo(TreeView1.SelectedNode.Value);

        GridView1.DataSource = directory.GetFiles();
        GridView1.DataBind();
    }
We learned how to create and delete files and directories and displaying all subdirectories and files in a disk, hierarchically in a TreeView.