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

Posted by: Suprotim Agarwal , on 4/20/2008, in Category WinForms & WinRT
Views: 261950
Abstract: In this article, we will explore some common text file operations using C# and VB.NET. This article has been requested by a long time reader of dotnetcurry.com. NET provides various classes like the File and FileInfo, to create, read, write and perform such similar operations on a text file. For example, you can use the Create() method of the File class to create a text file. The same could also be done using the CreateText() method of the FileInfo class. Similarly these classes also contain functionality to copy, move or delete a file. The trick is to find out when to use which class and for what purpose.
Create, Read, Write, Copy, Move and Delete a Text File using C# and VB.NET
 
In this article, we will explore some common text file operations using C# and VB.NET. This article has been requested by a long time reader of dotnetcurry.com. NET provides various classes like the File and FileInfo, to create, read, write and perform such similar operations on a text file. For example, you can use the Create() method of the File class to create a text file. The same could also be done using the CreateText() method of the FileInfo class. Similarly these classes also contain functionality to copy, move or delete a file. The trick is to find out when to use which class and for what purpose.
The ‘File’ class contains static methods and performs security checks on all the methods. The FileInfo contains instance methods and security check is not necessary. So this method is useful if you plan to use the same instance of the class in multiple operations.
However for copying, moving or deleting the files, the static methods are faster. Moreover, the Garbage Collector has less work to do when you use the File class, since the methods are static.
For reading and writing text files, we have some abstract classes like the TextReader and TextWriter classes. There are some useful classes like the StreamReader, StringReader, StreamWriter and StringWriter that derive from these abstract classes.
This article is by no means a comprehensive guide to demonstrate the capabilities of these classes. It should be treated as a ‘How do I’ kind of a series to demonstrate some of the capabilities of these classes. I will be giving some references at the end of this article, which should be read to gain a better understanding of these classes. Let us now see some code which demonstrates how to use these classes.
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";
VB.NET
Dim fileLoc As String = "c:\sample1.txt"
You would also need to reference the System.IO namespace in your project.
 
Create a Text File
 
C#
       // Create a Text File
        private void btnCreate_Click(object sender, EventArgs e)
        {
            FileStream fs = null;
            if (!File.Exists(fileLoc))
            {
                using (fs = File.Create(fileLoc))
                {
 
                }
            }
        }
VB.NET
         ' Create a Text File
            Private Sub btnCreate_Click(ByVal sender As Object, ByVal e As EventArgs)
                  Dim fs As FileStream = Nothing
                  If (Not File.Exists(fileLoc)) Then
                        fs = File.Create(fileLoc)
                        Using fs
 
                        End Using
                  End If
            End Sub
 
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");                  
                }
            }
        }
 
VB.NET
            ' Write to a Text File
            Private Sub btnWrite_Click(ByVal sender As Object, ByVal e As EventArgs)
                  If File.Exists(fileLoc) Then
                        Using sw As StreamWriter = New StreamWriter(fileLoc)
                              sw.Write("Some sample text for the file")
                        End Using
                  End If
            End Sub
 
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());
                }
            }
        }
VB.NET
            ' Read From a Text File
            Private Sub btnRead_Click(ByVal sender As Object, ByVal e As EventArgs)
                  If File.Exists(fileLoc) Then
                        Using tr As TextReader = New StreamReader(fileLoc)
                              MessageBox.Show(tr.ReadLine())
                        End Using
                  End If
            End Sub
 
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);
            }
        }
VB.NET
            ' Copy a Text File
            Private Sub btnCopy_Click(ByVal sender As Object, ByVal e As EventArgs)
                  Dim fileLocCopy As String = "d:\sample1.txt"
                  If File.Exists(fileLoc) Then
                        ' If file already exists in destination, delete it.
                        If File.Exists(fileLocCopy) Then
                              File.Delete(fileLocCopy)
                        End If
                        File.Copy(fileLoc, fileLocCopy)
                  End If
            End Sub
 
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);
            }
        }
VB.NET
            ' Move a Text file
            Private Sub btnMove_Click(ByVal sender As Object, ByVal e As EventArgs)
                  ' Create unique file name
                  Dim fileLocMove As String = "d:\sample1" & System.DateTime.Now.Ticks & ".txt"
                  If File.Exists(fileLoc) Then
                        File.Move(fileLoc, fileLocMove)
                  End If
            End Sub
 
Delete a Text File
 
C#
       // Delete a text file
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (File.Exists(fileLoc))
            {
                File.Delete(fileLoc);
            }
        }
VB.NET
         ' Delete a text file
            Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
                  If File.Exists(fileLoc) Then
                        File.Delete(fileLoc)
                  End If
            End Sub
 
We saw how to achieve some of the most common requirements while dealing with text files. Take a look at these reference links below to get a detailed understanding of the File and FileInfo class.
References :
 
I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by prasath R on Monday, April 28, 2008 2:39 AM
hi
really its super
its very very usefull for me and every one
thanks
prasath
Comment posted by Deepak Kataria on Saturday, June 21, 2008 4:27 AM
Hi

If want to cut and paste certain text from a text file.
How can we do that?

Regards,
Deepak Kataria
Comment posted by Abi on Saturday, August 23, 2008 3:11 PM
Hi

Im Going to Save a Photo In SqlServer2005 ,
How Can i do That?
Thanks
Comment posted by Suprotim Agarwal on Sunday, August 24, 2008 6:22 AM
Deepak: I apologize since i missed reading your comment.

Abi: To save an image in SQL Server, check this article
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129
Comment posted by mjafari on Tuesday, September 2, 2008 12:27 AM
i want a text special delete from file in C# ever file
Comment posted by rpb3 on Tuesday, September 2, 2008 3:50 PM
Any answer to Deepak's question?  I also need to easily remove (cut) specific text from a text file, hopefully without reading and writing the entire file.
Comment posted by Suprotim Agarwal on Tuesday, September 2, 2008 6:21 PM
rpb3: Try using the Clipboard.SetText("yourtext") and Clipboard.GetText() to achieve cut paste programmatically.
Comment posted by Suprotim Agarwal on Tuesday, September 2, 2008 6:23 PM
mjafari: Please reframe your question and ask it again. Thanks.
Comment posted by Dondon on Sunday, September 14, 2008 10:10 PM
how can I move a file to a mapped network drive?
Comment posted by gopal on Monday, December 1, 2008 2:04 AM
hi..
how to delete a particular word from a text file..

ex:ss.txt->document
(here i want to delete the word document only not the file)

i dont want to delete the whole text file..

its urgent..

thanx
gopal
Comment posted by mahesh on Wednesday, December 30, 2009 4:16 AM
hi,
I have to read the textfile which exits and then move it to second text file. zip both the file and write that in another text file and delete the file where we ziped.
Comment posted by Dhrupit on Wednesday, March 17, 2010 3:40 AM
I really thanking u for learning me such a good thing very brieffly.By heart i am thanking u.....
Comment posted by praveen on Friday, July 16, 2010 6:58 PM
this is clean and excellent topic to understand
Comment posted by andrea on Monday, August 2, 2010 7:08 AM
hi.. can you please tell me how to copy attributes of a non persistent cookie into a text file in asp.net using C#
Comment posted by mani on Friday, October 15, 2010 5:24 AM
vb.net coading
Comment posted by prabhu on Friday, October 15, 2010 5:25 AM
not fine...
Comment posted by bright on Friday, December 31, 2010 4:18 AM
This is really great and awesome.Many thanks to u buddy.
Comment posted by Fawad Mirza on Wednesday, August 3, 2011 9:24 AM
its really productive thanks buddy
Comment posted by Gaurav Balyan on Wednesday, March 14, 2012 7:15 AM
really Very Nice Tutorial
Comment posted by Saravanan on Tuesday, April 10, 2012 7:17 AM
How can i "programmatically",  using VB.NET/C#, set password security on PDF file to restrict users from editing it?
Comment posted by Hari on Friday, May 25, 2012 4:00 AM
This is fantastic, I am writing my first wpf for creating new text file on a file name and write some contents in. Hope I get there .!! :))
Comment posted by Rohit sharma on Sunday, June 24, 2012 5:50 AM
its working
but single escape sequence doesn't works in c#
so use double slash (\\) in file path
Comment posted by Ruchika on Tuesday, July 3, 2012 4:41 AM
Great Article...
Comment posted by vijay sharma on Friday, July 20, 2012 12:21 AM
great job sir,very nice.
Comment posted by Rakesh Rana on Thursday, July 26, 2012 1:15 AM
You have done great work sir.
Comment posted by murugan on Sunday, September 23, 2012 2:51 AM
sir,
how to read uploded text file ,read,update information in text file and also save file as same file.
help me sir,this module is one of my project in asp.NET.
reply to me sir.
Comment posted by deepak on Wednesday, September 26, 2012 4:38 AM
Great work!!!
Comment posted by gull on Sunday, December 30, 2012 9:25 PM
well done// its gud.....now i have book marked it....
Comment posted by ispider on Monday, March 11, 2013 11:45 PM
Really Super its very Helpfull For me
Comment posted by Manoj on Thursday, March 14, 2013 4:40 AM
U made a ease for searching and getting all in one place.

good one. thanks..
Comment posted by Area on Wednesday, May 22, 2013 7:38 AM
Good
Comment posted by shuaib on Wednesday, July 17, 2013 4:41 AM
Nice tutorial.... thanks... very helpful
Comment posted by mais n. on Tuesday, October 1, 2013 5:12 PM
thanx .. very helpful
but can i get simple code for retrive the deleted txtfile back
Comment posted by bala on Friday, March 7, 2014 12:37 AM
how to view the stored data on notepad after clicking open button
Comment posted by Md.Masum Billah on Friday, June 6, 2014 11:26 PM
Thanks for your information. because i am so help this information. it is so helpful in new programmer.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel