locked
My FileInfo accepts if condition even if there are no files in folder RRS feed

  • Question

  • User-1660589204 posted

    I have a folder from which I need to check if there are any ".trm" files and save them into DB. Below is my code:

    public async void PostValuesIntoDB()
            {
                DirectoryInfo info = new DirectoryInfo(path);            
                FileInfo[] fileInfos = info.GetFiles("*.trm");
                if (fileInfos != null)
                {
                    foreach (FileInfo fileInfo in fileInfos)
                    {
                        RsbfileDetail detail = new RsbfileDetail();
                        detail.Filename = fileInfo.Name;
                        detail.FileUrl = fileInfo.FullName;
                        detail.FileType = fileInfo.Extension;                    
                        detail.CreatedDate = fileInfo.CreationTime;                   
                        await _rSBRepository.Add(detail);
                    }
                }
                else
                {
                    Console.WriteLine("No trm file in destination folder");
                }
            }

    Right now, there are no files in my folder. But when I debug with breakpoint, the execution moves into if condition, then in foreach, it goes into fileinfos and then goes out of entire code not inserting any values in DB or displaying the message in else statement. I do not know what I did wrong. Please suggest. 

    Friday, November 13, 2020 2:24 PM

All replies

  • User475983607 posted

    ddesarajubyc

    Right now, there are no files in my folder. But when I debug with breakpoint, the execution moves into if condition, then in foreach, it goes into fileinfos and then goes out of entire code not inserting any values in DB or displaying the message in else statement. I do not know what I did wrong. Please suggest. 

    You're checking for NULL not an array without items.  A NULL reference is not the same as an empty object.

    if (fileInfos != null || fileInfos.Length > 0)

    Friday, November 13, 2020 4:29 PM
  • User-939850651 posted

    Hi ddesarajubyc,

    To determines whether any element of a sequence exists or satisfies a condition, you could use Enumerable.Any Method , something like

    if(fileInfos != null && fileInfos.Any()){
    //do something you want
    }

    As other members mentioned, you also use its length property to determine whether it is empty.

    if(fileInfos != null && fileInfos.Length > 0){
        //do something you want
    }

    Best regards,

    Xudong Peng

    Monday, November 16, 2020 6:49 AM