Difference between revisions of "Reading an writing test files in csharp"

From MyWiki
Jump to: navigation, search
(Created page with "'''Writing to a Text File'''<br> Listing 1: Writing Text Data to a File: TextFileWriter.cs<br> <source lang="csharp"> using System; using System.IO; namespace csharp_station....")
 
 
Line 19: Line 19:
 
             // close the stream
 
             // close the stream
 
             tw.Close();
 
             tw.Close();
 +
        }
 +
    }
 +
}
 +
</source>
 +
 +
 +
'''Reading From a Text File'''
 +
 +
Listing 2 shows how to read from a text file:<br>
 +
Listing 2: Reading Text Data from a File: TextFileReader.cs<br>
 +
<source lang="csharp">
 +
using System;
 +
using System.IO;
 +
 +
namespace csharp_station.howto
 +
{
 +
    class TextFileReader
 +
    {
 +
        static void Main(string[] args)
 +
        {
 +
            // create reader & open file
 +
            Textreader tr = new StreamReader("date.txt");
 +
 +
            // read a line of text
 +
            Console.WriteLine(tr.ReadLine());
 +
 +
            // close the stream
 +
            tr.Close();
 
         }
 
         }
 
     }
 
     }
 
}
 
}
 
</source>
 
</source>

Latest revision as of 21:50, 27 March 2015

Writing to a Text File
Listing 1: Writing Text Data to a File: TextFileWriter.cs

using System;
using System.IO;
 
namespace csharp_station.howto
{
    class TextFileWriter
    {
        static void Main(string[] args)
        {
            // create a writer and open the file
            TextWriter tw = new StreamWriter("date.txt");
 
            // write a line of text to the file
            tw.WriteLine(DateTime.Now);
 
            // close the stream
            tw.Close();
        }
    }
}


Reading From a Text File

Listing 2 shows how to read from a text file:
Listing 2: Reading Text Data from a File: TextFileReader.cs

using System;
using System.IO;
 
namespace csharp_station.howto
{
    class TextFileReader
    {
        static void Main(string[] args)
        {
            // create reader & open file
            Textreader tr = new StreamReader("date.txt");
 
            // read a line of text
            Console.WriteLine(tr.ReadLine());
 
            // close the stream
            tr.Close();
        }
    }
}