12.9 Appending Data to an Existing File

 <  Day Day Up  >  

You want to append data to a file.


Technique

The File class contains a method named AppendText that opens a file and sets the current starting point at the end. Any subsequent calls to Write will result in data being written to the end of the file. Additionally, if the file does not exist when AppendText is called, a new file is created:

 
 using System; using System.IO; namespace _9_AppendText {     class Class1     {         [STAThread]         static void Main(string[] args)         {             if( args.Length <= 0  args.Length > 2 )             {                 DisplayUsage();                 return;             }             if( File.Exists( args[0] ) == false )             {                 DisplayUsage();                 return;             }             StreamWriter sw = File.AppendText( args[0] );             sw.Write( args[1] );             sw.Close();             return;         }         static void DisplayUsage()         {             Console.WriteLine( "Usage: append <filename> \"<text>\"\n" );         }     } } 

Comments

Appending text is useful for applications that use some sort of logging mechanism for debugging purposes or those that utilize persistent data in some way. When using this method of file I/O, you should ensure that the application doesn't get carried away by writing too much data to a file without ever resetting the file so that the file size doesn't become too large. A popular technique for doing so is to create a circular logging file. Any time you write to the file, you should check the current file size. If the file size plus the size of the data you are planning to write is larger than a predetermined threshold value, then you must eliminate the data from the top of the file equal to the number of bytes you are adding to the bottom of the file. This move ensures that you always have the most recent data while still maintaining a suitable file size . Of course, if all the data is necessary and cannot be thrown out, then this point becomes unnecessary.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net