我的电脑在file.create后无法访问文件

问题描述:

我有一些代码可以删除一个文件,创建另一个文件(这样我可以覆盖它)并在上面写.

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?

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

because it is being used by another process

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

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.

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

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.