PROBLEM:
In my Program, when I try to loop the entire List of file found, I got exactly the 8 files on my List BUT displayed the same data value.
DEFINITION:
Class:
1.SearchFile.cs = has a method that accepts 2 parameters(PathToSearch and fileExtensionToSearch) then returns a List of “FileDetails” type.
public List<FileDetails> fileListFound = new List<FileDetails>();
public List<FileDetails> GetListFiles(string strPath, string strFileExtension)
{
DirectoryInfo dirInfo = new DirectoryInfo(strPath);
FileInfo[] files = dirInfo.GetFiles(strFileExtension, SearchOption.AllDirectories);
FileDetails fileDetails = new FileDetails();
foreach (FileInfo currentFile in files)
{
fileDetails.FileFullName = currentFile.FullName;
fileDetails.FileFullPath = strPath;
fileListFound.Add(fileDetails);
}
return fileListFound;
}
2.FileDetails.cs
class FileDetails
{
public string FileFullName { get; set; }
public string FileFullPath { get; set; }
public string FileType { get; set; }
}
-
My Main Program:
static void Main(string[] args) { string strPath = @"C:\Users\Public\Pictures\Sample Pictures"; FileCollection fileCollected = new FileCollection(); List<FileDetails> listOfFileFound = fileCollected.GetListFiles(strPath, "*.jpg"); foreach (FileDetails fileFound in listOfFileFound) { Console.WriteLine("Full Name: " + fileFound.FileFullName + ", Path:" + fileFound.FileFullPath); } Console.ReadLine(); }
NOTE: Im using Console application just to be clear with my Problem.
Sample Output: (8 files found)
…\Pictures**Tulips.jpg**
…\Pictures**Tulips.jpg**
…\Pictures**Tulips.jpg**
etc.. looped 8 times with the same output
NOTE: I can tell that the SearchFile.cs Class found the 8 different files then add it to my List and return it successfully by putting some breakpoints (Debug).
You are always modifying the same instance of
fileDetails. You need to allocate a new one inside the loop at every iteration:Since fileDetails is a reference that gets added to the list, modifying the same instance will cause all the values in the list to be the same.