Sunday, February 20, 2011

File handling in C#

You would need to reference the System.IO namespace in your project.
string
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

        // 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

        // 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

        // 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

        // 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

       // Delete a text file
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (File.Exists(fileLoc))
            {
                File.Delete(fileLoc);
            }
        }
 
fileLoc = @"c:\sample1.txt";

No comments:

Post a Comment