Create, Read, Write, Copy, Move and Delete a Text File using C#

Before you go ahead and use these methods, declare a class variable called ‘fileLoc’ which contains the filepath of the text file.
C#
string fileLoc = @”c:\sample1.txt”;
Create a Text File
       // Create a Text File
        private void btnCreate_Click(object sender, EventArgs e)
        {
            FileStream fs = null;
            if (!File.Exists(fileLoc))
            {
                using (fs = File.Create(fileLoc))
                {

                }
            }
        }
Write to a Text File
C#
        // Write to a Text File
        private void btnWrite_Click(object sender, EventArgs e)
        {
            if (File.Exists(fileLoc))
            {
                using (StreamWriter sw = new StreamWriter(fileLoc))
                {
                    sw.Write(“Some sample text for the file”);
                }
            }
        }
Read From a Text File
C#
        // Read From a Text File
        private void btnRead_Click(object sender, EventArgs e)
        {
            if (File.Exists(fileLoc))
            {
                using (TextReader tr = new StreamReader(fileLoc))
                {
                    MessageBox.Show(tr.ReadLine());
                }
            }
        }
Copy a Text File
C#
        // Copy a Text File
        private void btnCopy_Click(object sender, EventArgs e)
        {
            string fileLocCopy = @”d:\sample1.txt”;
            if (File.Exists(fileLoc))
            {
                // If file already exists in destination, delete it.
                if (File.Exists(fileLocCopy))
                    File.Delete(fileLocCopy);
                File.Copy(fileLoc, fileLocCopy);
            }
        }
Move a Text File
C#
        // Move a Text file
        private void btnMove_Click(object sender, EventArgs e)
        {
            // Create unique file name
            string fileLocMove = @”d:\sample1″ + System.DateTime.Now.Ticks + “.txt”;
            if (File.Exists(fileLoc))
            {
                File.Move(fileLoc, fileLocMove);
            }
        }
Delete a Text File
C#
       // Delete a text file
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (File.Exists(fileLoc))
            {
                File.Delete(fileLoc);
            }
        }

Collected from:

http://www.dotnetcurry.com/ShowArticle.aspx?ID=144

Advertisements
By simplemsexchange Posted in C#

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