Bpk7
Bpk7

Reputation: 27

File is currently in use. Can't write to it

So, i have this problem for a while and it's truly giving me headaches ... I want to download a string from a website, then save it so a file in my computer that i will create on the spot , let's say the file is D:\cars.txt , the file path by the way is Input(3) . I tried this but it just won't work! I ran out of ideas, can't find anything to make it work properly.

If Not IO.File.Exists(Input(3)) Then IO.File.Create(Input(3))

Dim str As String = WC.DownloadString(Input(2))

Using wrtr As IO.StreamWriter = New IO.StreamWriter(Input(3))

wrtr.Write(str)

System.Threading.Thread.Sleep(150)

wrtr.Close()

End Using

It won't write to the file because it's still in use, how can i make it work properly :( ?

Upvotes: 0

Views: 69

Answers (1)

Mat J
Mat J

Reputation: 5632

IO.File.Create(Input(3) creates or overwrites the file and returns a FileStream. From MSDN:

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

You can rewrite it as follows,

Dim str As String = WC.DownloadString(Input(2)) 
System.IO.File.WriteAllText(input(3),str)

Upvotes: 1

Related Questions