Read and Write to a file

bortiquai

Member
Joined
Jul 5, 2007
Messages
17
Programming Experience
Beginner
I am trying to read text from a text file, change it and the write it back to the same file. I am using the Io.streamReader and streamWriter.

I can't seem to get it to work because when it gets to the file.writeline(myFText), i receive an IOException, The file: "....MyFIle.txt" is in use"

I have tried adding file.close and file.dispose after ever instance of it, but it does not help.

Essentially, all i really want to do is add a line of text to the beginning of the file. If there is a better way to do that, i'd appreciate any suggestions.

Thank you
 
Beginning with .NET framework V2, the My namespace contains functions that ease file access:
VB.NET:
Dim fileContents As String = String.Empty
If My.Computer.FileSystem.FileExists("C:\Test.txt") Then
    fileContents = My.Computer.FileSystem.ReadAllText("C:\Test.txt")
End If
Dim myFText As String = "some random text"
fileContents = myFText & Environment.NewLine & fileContents
My.Computer.FileSystem.WriteAllText("C:\Test.txt", fileContents, False)
I created most of this code using code snippets. Right click in the code window and select 'Insert Snippet...' to view many more code snippets.
 
If you provide your code that is causing the problem, I can help. I have an idea as to what your problem is, but without your code to see exactly what is going on, I'm just guessing.
 
I am trying to read text from a text file, change it and the write it back to the same file. I am using the Io.streamReader and streamWriter.

I can't seem to get it to work because when it gets to the file.writeline(myFText), i receive an IOException, The file: "....MyFIle.txt" is in use"

I have tried adding file.close and file.dispose after ever instance of it, but it does not help.

Essentially, all i really want to do is add a line of text to the beginning of the file. If there is a better way to do that, i'd appreciate any suggestions.

Thank you

hi,
You must Create a filestream instance like below
Dim fs As New FileStream("C:\Documents and Settings\me.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)

if u use this code u will never get exception

How it Helped ! Reply.
 
You must Create a filestream instance like below
Dim fs As New FileStream("C:\Documents and Settings\me.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
That's not exactly true. As I posted above, using the My.Computer.FileSystem.ReadAllText method doesn't require the coder to create a FileStream instance. Although a FileStream instance is created by the method itself, the coder does not have to bother with creating or disposing of the instance.
 
Back
Top