a developer's notes – a semi-technical web development BLOG

September 5, 2011

How to write and append to a text file (C# .NET)

Filed under: C# — Duy Nguyen @ 2:33 pm
Tags: , , , , ,

How write to a text file and append more text from another function.


namespace TextFileWriter
{
    public partial class _Default : System.Web.UI.Page
    {
        //Create the StreamWriter object to do the writing
        StreamWriter sw;

        protected void Page_Load(object sender, EventArgs e)
        {
            string driveLetter = "c";
            string folder = "DEV_LOGS";
            string filename = "myFile";
            string fileExtension = ".txt";

            string path = SetFilePath(driveLetter, folder);
            string fullFilePathName = path + "\\" + filename + fileExtension;

            sw = CreateTextFile(fullFilePathName);

            sw.WriteLine("My first line of text");

            function1();

            sw.WriteLine("My third line of text");

            //be sure to close the stream and file or else
            //the file will be locked
            sw.Close();
        }

        public void function1()
        {
            sw.WriteLine("Second line of text");
        }

        public StreamWriter CreateTextFile(string fullFilePathName)
        {
            StreamWriter sw;

            // checks if the file exists
            if (!File.Exists(fullFilePathName))
            {
                sw = File.CreateText(fullFilePathName);
            }
            else
            {
                // file exists, append text to file
                sw = File.AppendText(fullFilePathName);
            }

            return sw;
        }

        public string SetFilePath(string driveLetter, string folder)
        {
            // Specify a "currently active folder" 
            string activeDir = driveLetter + @":\";

            //Create a new subfolder under the current active folder 
            string newPath = System.IO.Path.Combine(activeDir, folder);

            // Create the subfolder
            System.IO.Directory.CreateDirectory(newPath);

            return newPath;
        }
    }
}

Output:

My first line of text
Second line of text
My third line of text

You can also append like this:

namespace TextFileWriter
{
    public partial class _Default : System.Web.UI.Page
    {       
        //Create your objects here for global scope
        //Create the file
        FileStream theFile;

        //Create the StreamWriter object to do the writing
        StreamWriter sw;

        int x;

        protected void Page_Load(object sender, EventArgs e)
        {
            x = 0;

            for (int i = 0; i < 5; i++)
            {
                function1();
            }
        }

        public void function1()
        {
            x++;

            theFile = new FileStream(@"C:\DEV_LOGS\test.txt", FileMode.Append);

            sw = new StreamWriter(theFile);
            sw.WriteLine(x.ToString() + " line of text");

            sw.Close();
            theFile.Close();
        }
    }
}

Output:
1 line of text
2 line of text
3 line of text
4 line of text
5 line of text

Check this site out for different ways to open a file.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: