logo

.NET System.IO Read And Write Files Compared To Scripting.FileSystemObject

By Robbe Morris
Printer Friendly Version
View My Articles
1278 Views
    

Here's a beginners guide to reading/writing text or binary files in .NET using the System.IO namespace. Includes using recursion to create and traverse a folder hierarchy tree. Shows how to convert strings to binary and binary back to strings.


  Download Source Code Sample

I've gotten a lot of questions from vb 6.0 developers transitioning to .NET concerning the basics of working with files in .NET.  They come from the Scripting.FileSystemObject world.  So, I've worked up this sample to help you guys get started working with files in .NET.

You'll want to take notice of the "using" clause that is wrapped around the FileStream, BinaryReader, BinaryWriter, StreamReader, and StreamWriter oriented code blocks.

The using clause forces .NET to always call the .Dispose() method on classes that implement the IDisposable interface which these do.  The .Dispose() method will get called whether an error occurred or not.  If you disassemble the .net framework System.IO assembly, you'll find that the .Dispose() method of these classes always calls its base class Stream .Dispose() method.

The Stream .Dispose() method always calls its .Close() method which closes any file connections it may still have.  Most of the .NET classes that implement IDisposable will eventually get down to a .Close() method somewhere in the class hierarchy.  However, you can't always be certain that 3rd party or open source controls/assemblies will do the same.

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using System.Text;

namespace FileSystemObject
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] binary = null;
            string folder = @"C:\temp";
            string text = "line 1\nline 2\nline 3";
            string textFileName = "test.txt";
            string binaryFileName = "test.dat";
            string fullFileName = "";
     
            try
            {
                  fullFileName = Path.Combine(folder, textFileName);
                  
                  // Creating directory
                  
                  if (!Directory.Exists(folder))
                  {
                      Directory.CreateDirectory(folder);
                  } 
                  
                  WriteTextFile(fullFileName,text);
                  
                  text = ReadTextFile(fullFileName);
                  
                  Console.WriteLine(text);
                  
                  // Sample to delete file
                  
                  if (File.Exists(fullFileName))
                  {
                     File.Delete(fullFileName);
                  }

                  WriteTextFile(fullFileName, text);
                  
                  DisplayTextFileLineByLine(fullFileName);

                  // Binary/Image file samples
                  
                  fullFileName = Path.Combine(folder, binaryFileName);
                  
                  // Convert text string to sample binary
                  
                  UTF8Encoding encoding = new UTF8Encoding();
                  
                  binary = encoding.GetBytes(text);
   
                  // Write the binary contents to a binary file
                  
                  WriteBinaryFile(fullFileName,binary);
                  
                  // Read the entire binary file into a byte[]
                  
                  binary = ReadBinaryFile(fullFileName);
                  
                  if (binary != null)
                  {
                     // Convert the byte[] back to a string
                     text = encoding.GetString(binary, 0, binary.Length);
                  }
                  
                  Console.Write(text);
                  Console.WriteLine("");
                  
                  DirectoryInfo directory = new DirectoryInfo(folder);
                  
                  CreateFolderTree(directory,6);
                  
                  DisplayFolderNames(directory);
                  
                  Console.WriteLine("done");
                   
            }
            catch (Exception ex)
            {
               Console.WriteLine(ex.Message);
            }
            finally {  Console.ReadLine(); }
        }

        #region Read Binary File
        public static byte[] ReadBinaryFile(string fileName)
        {
            try
            {
                using (FileStream fs = new FileStream(fileName,
                                                      FileMode.Open,
                                                      FileAccess.Read))
                {
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        return br.ReadBytes((int)fs.Length);
                    }
                }
            }
            catch (Exception) { throw; }
        }
        #endregion

        #region Write Binary File
        public static void WriteBinaryFile(string fileName, byte[] binary)
        {
            try
            {
                using (FileStream fs = new FileStream(fileName,FileMode.Create))
                {  
                    using (BinaryWriter bw = new BinaryWriter(fs))
                    {
                        bw.Write(binary);
                    }
                 }
            }
            catch (Exception) { throw; }
        }
        #endregion
        
        #region Write Text File
        public static void WriteTextFile(string fileName,string contents)
        {
           try
           {
               using(StreamWriter sw = new StreamWriter(fileName,false))
               {
                  sw.Write(contents);
               } 
           }
           catch (Exception) { throw; }
        }
        #endregion

        #region Read Text File
        public static string ReadTextFile(string fileName)
        {
            try
            {
                using (StreamReader sr = new StreamReader(fileName))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception) { throw; }
        }
        #endregion

        #region Display Text File Line By Line
        public static void DisplayTextFileLineByLine(string fileName)
        {
    
            try
            {
                using (StreamReader sr = new StreamReader(fileName))
                {
                    while(sr.Peek()>0)
                    { 
                      Console.WriteLine(sr.ReadLine());  
                    }
      
                }
            }
            catch (Exception) { throw; }
        }
        #endregion

        #region Create Folder Tree
        public static void CreateFolderTree(DirectoryInfo directory,
                                            int numberOfSubFolders)
        {
            string folderName  ="";
            
            try
            {

                for (int i = 0; i < numberOfSubFolders; i++)
                {
                
                    folderName = Path.Combine(directory.FullName,
"test" + i.ToString()); if (!Directory.Exists(folderName)) { CreateFolderTree(Directory.CreateDirectory(folderName),
i-1); } } } catch (Exception) { throw; } } #endregion #region Display Folder Names public static void DisplayFolderNames(DirectoryInfo directory) { DirectoryInfo[] directories = null; FileInfo[] files = null; try { files = directory.GetFiles(); if (files != null) { for (int i = 0; i < files.Length; i++) { Console.WriteLine(files[i].FullName); } } directories = directory.GetDirectories("*test*"); if (directories == null) { return; } for(int i=0;i<directories.Length;i++) { Console.WriteLine(directories[i].FullName); DisplayFolderNames(directories[i]); } } catch (Exception) { throw; } } #endregion } }

Biography - Robbe Morris
Robbe has been a Microsoft MVP in C# since 2004. He is also the co-founder of EggHeadCafe.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.


Didn't Find The Answer You Were Looking For?

EggHeadCafe has experts online right now that may know the answer to your question.  We pay them a bonus for answering as many questions as they can.  So, why not help them and yourself by becoming a member (free) and ask them your question right now?
Ask Question In Live Forum

If you have an OpenID and do not want to become a member of the EggHeadCafe forum, you can also sign on to Chat Chaos and post your question to our real time Silverlight chat application.
Ask Question In Chat Chaos

Article Discussion: .NET System.IO FAQ Compared To Scripting.FileSystemObject
Robbe Morris posted at Wednesday, December 06, 2006 7:59 PM
Original Article
 

Looks like it was moderated before the user flagged it as helpful
Robbe Morris replied at Wednesday, May 27, 2009 7:21 AM

There were still open posts in that thread to be moderated and I'm sure the moderator would have

revised it (as we often do).  I just did.

 

You pasted these out of a link
Robbe Morris replied at Thursday, May 28, 2009 3:56 PM
and didn't offer an insight of your own.
 

If you post a link, you must give some details as to what
Robbe Morris replied at Monday, June 15, 2009 6:59 AM
is in the link that you think is valuable to the original poster's question.  This is stated on our rules page.  In this case, you were the third or fourth responder to the thread.  Just simply posting a link doesn't tell the moderator why you even bothered.
 






  $1000 Contest    [)ia6l0 iii - $228  |  Jonathan VH - $161  |  Huggy Bear - $135  |  F Cali - $95  |  egg egg - $94  |  more Advertise  |  Privacy  |   (c) 2010