0

I want to get a list of files in a directory except those files being pasted, but my code doesn't work:

static List<string> getListFile(string directory)
{
    List<string> listFile = new List<string>();
    string[] filePaths = Directory.GetFiles(directory);
    foreach (string s in filePaths)
    {
        FileInfo fileInfo = new FileInfo(s);
        long size1 = fileInfo.Length;
        Thread.Sleep(2000);
        fileInfo = new FileInfo(s);
        long size2 = fileInfo.Length;
        if (size1 == size2)//This is always true
        {
            listFile.Add(s);
        }
    }
    return listFile;
}
M.Babcock
  • 18,753
  • 6
  • 54
  • 84
  • Please describe what you expect the code above to do and what it's doing that you don't expect? – M.Babcock Dec 20 '13 at 02:50
  • As far as I know, a file will not appear in the directory until it has been 'copied' in full (no partials), so your goal of ignoring a file if size has changed in 2 seconds is pointless. – JuStDaN Dec 20 '13 at 02:52
  • I have an application, every 30 second, it get list file to process (let says list file in folder A). But I don't want to list the files are being copied from folder B to folder A. – Nguyễn Văn Quang Dec 20 '13 at 02:59

1 Answers1

1

I don't think files being copied will be listed if the targetd directory is the destination, so your safe-check is worthless.

Edit: given the further explaining of the author, if you want to check if a file is being copied, use the exception to do so:

 foreach (string s in filePaths)
                {
                    try
                    {
                        using (FileStream fileStream = new FileStream(s, FileMode.Open, FileAccess.Read))
                        {
                            //Do no thing
                            listFile.Add(s);
                        }
                    }
                    catch
                    {
                      // file can't access, because it is being used by another process(pasteing).
                    }
                }

Original answer

Community
  • 1
  • 1
Rodrigo Silva
  • 432
  • 1
  • 6
  • 18