文件正由另一个进程使用

时间:2011-07-20 09:28:33

标签: c#

我正在开发ac#应用程序,后端作为sqlite。在我的应用程序中,我有一个干净的数据库选项。这意味着当前.db文件将使用File.Delete方法删除,并再次使用File.create方法创建空数据库现在让我解释一下这个问题。

要执行cleandatabse任务,我必须停止正在运行的所有进程,之后如果我点击干净数据库它会抛出一个文件无法删除的错误,它正在被另一个进程使用。我能够停止正在运行的所有线程。

不知何故,我能够找到哪个进程是blocikng文件,

foreach (var process in Process.GetProcesses()) {
                var files = GetFilesLockedBy(process);
                if (files.Contains(filePath))
                {
                    procs.Add(process);
                    Console.WriteLine(process.ProcessName);
                    process.Kill();
                    File.Delete(filePath);
                }
            }

但是在上面的代码中我使用了process.Kill,它关闭了我正在运行的窗体。 没有使用杀戮,我试着关闭并处理哪个对我不起作用。

是否可以帮助我在不关闭应用程序的情况下从进程中释放文件,然后删除db文件。

提前谢谢

祝你好运

桑吉塔。

3 个答案:

答案 0 :(得分:4)

您应该确保关闭每个打开它的流:

using (Stream str = File.Create("C:\\h.txt"))
{
// your code here
} // the stream will be automatically closed here

如果您不添加此using语句,即使您手动关闭它,也会导致很多错误str.Close();

答案 1 :(得分:3)

Streams是一次性类型,您必须通过using语法手动管理其生命周期,例如:

using (StreamReader f = new ...) {
}

...或者更详细地说(如果在不同的代码块/函数中分配和删除Stream,则需要此语法):

try {
    StreamReader f = new ...;
    ...
} finally {
    if (null != f) f.Dispose();
}

......或者通过使持有类本身为IDisposable。另见What Your Mother Never Told You About Resource Deallocation


有趣的是,这似乎是其中一个https://stackoverflow.com/questions/2245196/c-urban-myths/2245382#2245382的实际化身:

  

0)在C ++中,你必须搞乱指针,这是旧的和危险的,使用C#

     

Gee,#include boost/shared_ptr>或其中之一。实际上,通常更容易在你的C#中产生混乱:

static void Main () {
    foo();
    bar();
}
static void foo () {
    var f = new StreamWriter ("hello.txt");
    f.Write ("hello world");
}
static void bar () {
    var f = new StreamReader ("hello.txt");
    Console.WriteLine (f.ReadToEnd ());
}
  
    

“未处理的IOException:进程无法访问文件'hello.txt',因为它正由另一个进程使用。”

  
     

那些声称,顺便说一句,往往是那些碰巧从未听说过RAII的人,以及即使没有智能指针也能取得多大成就。

答案 2 :(得分:0)

不确定,但您可能会在当前流程中致电Kill。 编辑:循环后调用Delte。 试试这个:

int currentProcessId = Process.GetCurrentProcess().Id;
foreach (var process in Process.GetProcesses()) {
              if (process.Id != currentProcessId)
              {
                var files = GetFilesLockedBy(process);
                if (files.Contains(filePath))
                {
                    procs.Add(process);
                    Console.WriteLine(process.ProcessName);
                    process.Kill();
                }
              }
            }
File.Delete(filePath);

此外,Close不会终止进程,您必须调用CloseMainWindow或Kill。