Friday, 1 November 2013

C# - Various Ways to Write in a Text File

In C# we can create a file and write the content in various ways,In this article we will see that how we can create a file in various ways, check the existence of file in computer , delete the file and rename the file

Create a File and Write the Content ;

Way 1 :
In this example we are going to create a File and write the content in each and every line with increment in number up to 10000 lines in a second.

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <=10000; i++)
            {
                WriteLog(string.Format(" Value {0} "+Environment.NewLine,i));
            }
            Console.Read();
        }

        static void WriteLog(string message)
        {
            File.AppendAllText(@"D:\sample.txt", message);
        }
    }


 Output:

Way 2:
This example uses the filestream class in which we can change the settings options , and streamwriter class to write the content in file.   writer.Flush(); method is important if this method is not called then file will create but content will not write. if close is mentioned then at finally content will be write in file.

static void Main(string[] args)
        {
            FileStream fs=new FileStream(@"D:\sample.txt",FileMode.Append);
            StreamWriter writer = new StreamWriter(fs);
            writer.WriteLine("Hi this is testing application !/");
            writer.WriteLine("I am Rajesh");
            writer.WriteLine(":)");
            writer.Flush();
            writer.Close();
            fs.Close();
            Console.Read();
        }







Use File.Delete(@"D:\sample.txt") method to delete a file in particular path

To Check whether File is present in the particular path use the File.Exists(@"D:\sample.txt") method.

I Hope from this article you will learn how to create  a text file and write the content in it. as well delete and file exists 




No comments:

Post a Comment