Question Create txt file and write to it without access denied lock?

Bill-e

Member
Joined
Jan 24, 2012
Messages
9
Programming Experience
3-5
Hey,

1. I have to create a file.
2. Then I want to write a string into the text file.

I can do part 1 no problem with:
File.Create(strFilePath)
But when I try part 2 to write to the file it won't allow this as it's still being used:
sw = File.AppendText(strFileName)
sw.WriteLine(strCode)
sw.Flush()
sw.Close()

My code in part 2 works fine on a file that hasn't just been created.

How do I release the file from the File object?

There doesn't seem to be a .close or .flush option...?

Thanks.
 
No need to use File.Create at all.

VB.NET:
        Dim stringToWrite = "String written to new file"

        Using sw As New IO.StreamWriter("C:\Temp\FileCreatedByStreamWriter.txt")
            sw.WriteLine(stringToWrite)
        End Using

Here's the documentation for StreamWriter Class (System.IO). You'll see in their example that they're creating a new file as well to write directory names to.
 
Back
Top