29 Ocak 2011 Cumartesi

Basic File Operations in C#


Hello code lovers,


In this article, we will find out how to do basic file operations. As you know, these operations become very important for us especially where there is no connection to a database. So let's see the codes !


1. Writing to a text file: This operation writes the given content to a text file. If the file exists, it overwrites it, else generates a new text file.Let's see the code,


StreamWriter sw = new StreamWriter("C:/mytext.txt");
sw.WriteLine("I hate hello world :)");
sw.Close(); // This line is important, because if we don't close connection, it //doesn't allow to do a second operation on this file.


2. Reading content from a file: This operation reads content from a file.


StreamReader sr = new StreamReader("C:/mytext.txt");
string[] content=new string[20];
int i=0;

while(content!=null){

content[i]=sr.ReadLine();
i++;

}

3. Appending content to a text file: It appends the given content to a text file. Likely writing operation, it generates a the file when it does not exist.


StreamWriter sr = File.AppendText("C:/mytext.txt");
sr.WriteLine("My text is here !");
sr.Close();


See you at another article !

Hiç yorum yok:

Yorum Gönder