my.computer在file.create之后无法访问文件

fra*_*000 4 vb.net

我有一些代码删除一个文件,另一个(所以我可以覆盖它)并写上它.

            My.Computer.FileSystem.DeleteFile("./pass")
            File.Create("./pass")
            My.Computer.FileSystem.WriteAllText("./pass", MaskedTextBox1.Text, True)
Run Code Online (Sandbox Code Playgroud)

当它写出文字时,它说:

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.
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题,或者可能只是覆盖文件而不删除并重新创建文件?

Han*_*ant 7

因为它正被另一个进程使用

这并不完全准确,它正由您的流程使用.File.Create()返回一个FileStream对象.你没有调用它的Close()方法,因此它仍在使用中.File.Create().Close()可以解决问题.

但是在这里使用File.Create()没有意义,FileSystem.WriteAllText()已经创建了该文件.删除文件也没有意义,WriteAllText()会覆盖文件.所以只需删除前两个语句来解决您的问题.