通过c#移动文件后,缩略图仍然存在

时间:2014-01-30 11:00:59

标签: c# file-io console

我正在使用FileSystemWatcher来监视是否在该目录中复制了任何文件。如果任何文件被复制,我想将其移动到其他工作目录,但该缩略图仍保留在该目录中。当我点击它时,我收到一条错误消息,指出“Cannot file XYZ file”。手动刷新该目录后,此文件将被删除。任何建议如何删除该缩略图。

这是我的代码

class Program
{
    static void Main(string[] args)
    {
        System.IO.FileSystemWatcher objFileSystemWatcher = new System.IO.FileSystemWatcher(@"C:\Users\Test\");
        objFileSystemWatcher.EnableRaisingEvents = true;
        objFileSystemWatcher.IncludeSubdirectories = true;
        objFileSystemWatcher.Created += new FileSystemEventHandler(OnCreated);
        Console.ReadLine();
    }

    public static void OnCreated(object source, FileSystemEventArgs e)
    {
        FileInfo fInfo = new FileInfo(e.FullPath);
        while (IsFileLocked(fInfo))
        {
            Thread.Sleep(500);
        }
        Console.WriteLine("{0}, with path {1} has been {2}", e.Name, e.FullPath, e.ChangeType);
    }

    static bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;
        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            Console.WriteLine("In catch");
            return true;
        }
        finally
        {
            Console.WriteLine("In finally");
            if (stream != null)
            {
                stream.Close();
                file.MoveTo(@"D:\MoveFolder\" + file.Name);
            }
        }
        return false;
    }

    public static void OnRenamed(object source, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine(" {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
}

0 个答案:

没有答案