IO exeption when trying to write to or read from a file

Hello

When my program tries to read or write to a file I get the IO exception error, it says the file is in use by another program.

This is the code I use (test code). The file gets created and then I get the error.

Dim file As System.IO.FileStream

file = System.IO.File.Create("c:\test.txt")

My.Computer.FileSystem.WriteAllText("c:\test.txt", "test text", True)

Dim filereader As String

filereader = My.Computer.FileSystem.ReadAllText("c:\test.txt")

Label1.Text = (filereader)

Anyone know how to fix this

Bye and thanks in advance.



Answer this question

IO exeption when trying to write to or read from a file

  • Visualcpp

    // file = System.IO.File.Create("c:\test.txt")

    This creates a file

    //My.Computer.FileSystem.WriteAllText("c:\test.txt", "test text", True)

    This helper method attempts to create a file and write text to it. Note that it does not take 'file' as a parameter.

    Therefore, you're trying to create it twice, which fails. The helper methods are there mostly I think because unlike C++, in .NET, you have to remember to close a file, or you won't know when ( if ever ) you can access it again while your program runs.



  • Domino

    Thanks, you were right the problem, the write to file paramater also made a file.

    For anyone that want to have the fixed code here it is:

    My.Computer.FileSystem.WriteAllText("c:\test.txt", "test text", True)

    Dim filereader As String

    filereader = My.Computer.FileSystem.ReadAllText("c:\test.txt")

    Label1.Text = (filereader)

    Bye


  • IO exeption when trying to write to or read from a file