如何在不打开文件的情况下使用C#检查文件是否已复制完成

5

我需要在C#中检查文件是否已经复制完成。有没有像iscopycompleted这样的事件?我需要在不打开文件的情况下进行检查。许多示例都是通过打开文件来进行的。

文件属性何时创建?在复制过程中,文件的属性是什么?有没有办法使用文件属性来检查文件是否正在复制?

我已经使用以下代码进行了检查。

FileAttribute atr=File.getAttribute("FilePath");

在复制完成后,我得到的文件属性为存档。


1
复制是如何启动的? - Spence
请查看此帖子 http://stackoverflow.com/questions/12588605/is-file-being-copied-right-now - Sievajet
当代码被(成功地)执行且没有抛出任何异常时,你就知道了。 - kevintjuh93
我正在尝试使用文件夹监视器。在这里,我正在监视一个文件夹,如果有文件进入该文件夹,我需要将其移动到另一个文件夹中。如果我移动的文件没有完全复制,我会收到错误提示,例如“另一个进程正在使用该文件”。因此,我需要检查文件是否已完全复制,而不需要使用file.open并不断检查。 - Amal
考虑使用 FileSystemWatcher 类。它会在文件目录发生更改时引发事件。 - Amit Kumar Ghosh
是的,我只使用了FilesystemWatcher,但当文件被更改或大小增加时,Changed事件会触发。但它并不表示文件复制已完成。 - Amal
4个回答

1
你可以比较两个文件的大小。
long length1 = new System.IO.FileInfo("fromFile").Length;

//code for moving file here

long length2;
do{
    length2 = new System.IO.FileInfo("toFile").Length;
} while (length1!=length2);

1
这个函数会一直工作,直到文件复制完成。
private bool CheckFileHasCopied(string FilePath)
    {
        try
        {
            if (File.Exists(FilePath))
                using (File.OpenRead(FilePath))
                {
                    return true;
                }
            else
                return false;
        }
        catch (Exception)
        {
            Thread.Sleep(100);
            return CheckFileHasCopied(FilePath);
        }

    }

如果我们正在同时复制多个文件,那么我们该怎么知道要复制多少个文件,并在所有文件都复制完成后开始处理? - Raul Marquez
如果你需要复制多个文件,那么没有问题,但是当你需要处理这些文件时,可以使用CheckFileHasCopied。你可以使用FileSystemWatcher来检测和计算进入文件夹的每个文件,并在完成复制后进行处理。 - Tuan Zaidi

0

这就是你要找的,只需控制 FileSystemWatcher 创建事件:

private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
    bool flag = true;
    while(flag)
    {
        try
        {
            File.Move(e.FullPath, @"C:\NewLocation\" + e.Name);
            flag = false;
        }
        catch { }
    }
}

0
如果您想检查文件是否已从一个位置移动到另一个位置,可以尝试以下操作。
//Store the location of your destination folder here with FileName
string Destination = "Destination_Location/"+FileName;

//Now get the entire Destination Address with FileName using Server.MapPath
string FullPath = Server.MapPath(Destination );

//Now you can use File.Exists condition to check whether file is present in your Destination location or not    
if (File.Exists(FullPath))
{
   //File copy is completed
}
else
{
   //File not present
}

不是一个好的方法。因为文件仍然存在,但它正在被其他进程使用。所以File.Exists返回true,但该文件正在使用中,无法移动。 - Inside Man
我刚刚提供了移动文件的逻辑,一旦文件上的所有操作完成,他就可以移动文件。为了检查文件是否已经移动到目标位置,他可以使用File.Exists方法。如果它返回true,那么说明文件已成功移动到目标位置。如果它返回false,那么说明文件没有被复制,这时他可以再次尝试移动文件。 - Amar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接