正在被另一个进程使用的文件,我必须关闭它?怎么样? [英] The file is being used by another process, I must close it? How?

查看:287
本文介绍了正在被另一个进程使用的文件,我必须关闭它?怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是文本文件,有一些数据存在供以后的目的。所以,我做的是,以检查文件是否存在,如果不是我创建一个新的文件,当我需要。这给了我错误说我的档案仍在使用由不同的过程,但我不知道这是为什么。

I am using a text file to have some data there for later purposes. So what I do is to check if file exists, if not I am creating a new file when I need. This gives me error saying that my file is still being used by a different process, but I'm not sure why that is.

这是我要做的事。在这里,我检查文件是否存在程序运行时,这将启动:

This is how I do it. Here, I am checking if file exists which starts when program runs:

    private void CreateLastOpenFile()
    {
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }

        if (!File.Exists(file))
        {
            File.Create(file);
        }
    }

现在,我加入了一些数据,它同时检查或创建一个新文件(我有这个在我的程序2处):

Now, I am adding some data to it while checking or creating a new file (I am having this in 2 places in my program):

CreateLastOpenFile();
File.WriteAllText(file, data);



可能是什么错在这里?我已阅读从网络的一些例子,但没有看到有关关闭任何文件事情。

What could be wrong here? I have read some examples from the Net, but didn't see anything about closing any files.

推荐答案

试试这个。这将文件创建

Try this. This will close the opened stream during file creation

 if (!File.Exists(file))
        {
         FileStream str = File.Create(file);
         str.Close();
        }

这篇关于正在被另一个进程使用的文件,我必须关闭它?怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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