Myanmar IT Resource Forum
Myanmar IT Resource Forum
Myanmar IT Resource Forum

You are not connected. Please login or register

View previous topic View next topic Go down  Message [Page 1 of 1]

1Write To File in C# Empty Write To File in C# 6th October 2009, 8:18 pm

sHa92

sHa92
Founder



Founder
Write To File in C#
Author- Shabbir

Today we will create a console application written in C# for writing to files.
We will use the StreamWriter class that is implemented in .Net Framework.

Create new C# project (Ctrl+Shift+N), and choose Console Application from the Templates menu on the right.
The editor will create the main code
Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace WriteToFile
{
  class Program
  {
    static void Main(string[] args)
    {
 
    }
  }
}

Below the using System.Text; add this code

Code:
using System.IO;

That is the namespace where the StreamWriter class is declared in.

Now, in the Main function add the folowing code

Code:
StreamWriter sw = new StreamWriter("text.txt");
sw.WriteLine(DateTime.Now + " : The program is executed");
sw.Write("Code");
sw.Write("It");
sw.WriteLine("Well.com");
sw.Close();

As you see, in the above code we are creating an object from the StreamWriter class, and we tell the object to write in the file "text.txt" (if the file doesn't exist, it will be created). So we are writing some text in the file using the WriteLine() and Write() functions. It's used and the DateTime class, so in the text file will be written the time where the file was changed.
Very important is, when we finish with writing, we must close the file with sw.Close(). If the file isn't closed, we are leaving an opened handle, so other programms can't access that file.

This will be written to file

Code:
29.04.2008 13:00:22 : The program is executed
[You must be registered and logged in to see this link.]

Every time we execute the program, the file will be erased, and then written again.
If you don't want this, make this changes in the creating the StreamWriter object sw

Code:
StreamWriter sw = new StreamWriter("text.txt", true);

http://www.myanmaritresource.info

View previous topic View next topic Back to top  Message [Page 1 of 1]

Permissions in this forum:
You cannot reply to topics in this forum

 

Create a forum on Forumotion | ©phpBB | Free forum support | Report an abuse | Forumotion.com