Reputation: 123
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;
}
Upvotes: 0
Views: 105
Reputation: 432
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).
}
}
Upvotes: 1