我的电脑在file.create后无法访问文件 [英] My.computer can't access file after file.create

查看:32
本文介绍了我的电脑在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.

这篇关于我的电脑在file.create后无法访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆