Reputation: 37
I have the following code where I am trying to enumerate through files on a shared drive, collect properties for each file, and then return each entry from that collection.
Visual Studio gives me "CS0161: 'Program.EnumerateYourFiles(string)': not all code paths return a value." error when I hover over the EnumerateYourFiles method. I am guessing that it has to do with the fact that the "l" variable I am trying to return is out-of-scope. How do I get that "l" variable into scope so it returns for the function?
using System;
using System.IO;
using System.Collections.Generic;
namespace FileShareMachine
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(EnumerateYourFiles(@"E:\"));
}
public static object EnumerateYourFiles(string pathToSearch)
{
string filePath = pathToSearch;
DirectoryInfo currentParentFileList = new DirectoryInfo(filePath);
DirectoryInfo[] listOfSubDirectories = currentParentFileList.GetDirectories();
List<string> listOfAllFiles = new System.Collections.Generic.List<string>();
foreach (var parentPath in listOfSubDirectories)
{
string pathForEnumeration = parentPath.ToString();
DirectoryInfo individualSubFolder = new DirectoryInfo(pathForEnumeration);
try
{
foreach (var eachFile in individualSubFolder.EnumerateFiles("*", SearchOption.AllDirectories))
{
string individualPaths = eachFile.FullName.ToString();
string lastAccessed = eachFile.LastAccessTime.ToString();
string fileSize = eachFile.Length.ToString();
string creationTime = eachFile.CreationTime.ToString();
string lastWriteTime = eachFile.LastWriteTime.ToString();
string fileDirectory = eachFile.Directory.ToString();
//The following works like a dream. This is how you write to a file. You need an array or list
listOfAllFiles.Add(individualPaths);
listOfAllFiles.Add(fileSize);
listOfAllFiles.Add(fileDirectory);
listOfAllFiles.Add(creationTime);
listOfAllFiles.Add(lastAccessed);
listOfAllFiles.Add(lastWriteTime);
}
}
catch (System.UnauthorizedAccessException)
{
bool errorThrown = true;
if (errorThrown)
{
Console.WriteLine("The following path had an access error {0}", individualSubFolder);
continue;
}
else
{
continue;
}
}
}
//return listOfSubDirectories;
foreach(object l in listOfAllFiles)
{
return l;
}
}
}
}
Upvotes: 0
Views: 323
Reputation: 180858
foreach(object l in listOfAllFiles)
{
return l;
}
isn't going to work.
Try
return listOfAllFiles
instead.
Consider returning something other than an object
, like IEnumerable<string>
, unless your use case requires object
(it's not unprecedented; there are places in WPF that are like that).
If you're trying to return one item from the list each time you call the method, try
yield return l;
instead. Your method should then return a string
.
Upvotes: 1