相关疑难解决方法(0)

有没有办法检查文件是否正在使用?

我正在用C#编写一个需要重复访问1个图像文件的程序.大部分时间它都可以工作,但如果我的计算机运行速度很快,它会在将文件保存回文件系统之前尝试访问该文件并抛出错误:"另一个进程正在使用的文件".

我想找到解决这个问题的方法,但是我所有的谷歌搜索都只是通过使用异常处理来创建检查.这违背了我的宗教信仰,所以我想知道是否有人有更好的方法呢?

.net c# file-io file file-locking

809
推荐指数
11
解决办法
49万
查看次数

如何等到File.Exists?

我有一个应用程序,在所选文件夹中侦听*.log文件.我用过FileSystemWatcher.

但有一个问题.负责制作该文件的另一个应用程序采取以下步骤:

  1. 制作一个*.gz文件
  2. 将其解压缩到txt文件(一些随机文件名)
  3. 将*.txt名称更改为具有*.log扩展名的正确名称.

我无法改变这种行为.

所以我FileSystemWatcher为*.gz和*.txt文件做了2 秒.为什么?因为此应用程序有时不解压缩gz文件,有时不会将txt文件重命名为最终的*.log文件.

FileSystemWatcher2 捕获txt文件,然后(在大多数情况下,它被重命名为在接下来的1000毫秒登录)我需要等待一段时间来检查是否存在txt文件(如果没有,它似乎被重命名为最终的*.log文件).

问题是,如何检查文件是否存在而不Thread.Sleep()阻止UI冻结?

我希望很清楚,如果不是,我会尝试更好地描述它.我认为这是一个复杂的问题.

一些代码示例:

Watz for gz文件:

private void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
   //this is for gz files in case if gz file is not unpacked automatically by other app
   //I need to wait and check if gz was unpacked, if not, unpack it by myself,
   //then txt watcher will catch that
   Thread.Sleep(5000);
   if (File.Exists(e.FullPath))
   {
      try
      {
         byte[] dataBuffer = new byte[4096];
         using …
Run Code Online (Sandbox Code Playgroud)

c# multithreading sleep file exists

14
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

file ×2

.net ×1

exists ×1

file-io ×1

file-locking ×1

multithreading ×1

sleep ×1