My.computer can't access file after file.creat

2020-07-18 05:40发布

问题:

I have some code to delete a file, make another one (so i can overwrite it) and write on it.

            My.Computer.FileSystem.DeleteFile("./pass")
            File.Create("./pass")
            My.Computer.FileSystem.WriteAllText("./pass", MaskedTextBox1.Text, True)

When it gets to write the text it says :

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file '[path]\pass' because it is being used by another process.

Is there a way to solve this or maybe a way to just overwrite the file without deleting and making it again?

回答1:

because it is being used by another process

That's not entirely accurate, it is in use by your process. File.Create() returns a FileStream object. You didn't call its Close() method so it is still in use. File.Create().Close() would solve the problem.

But there's no point to using File.Create() here, the FileSystem.WriteAllText() already creates the file. No point in deleting the file either, WriteAllText() overwrites the file. So just remove the first two statements to fix your problem.



标签: vb.net