adplus-dvertising

Cannot access a string from a method outside of main

Asked 2 months ago
Viewed 21 times
c#

I'm trying to access the filePaths string from the listFilesInDirectory method outside of the main but it is giving me the following error: "The name 'filePaths' does not exist in the current context"

internal class Program
    {
        static void listFilesInDirectory(string workingDirectory)
        {
            // Let's find some files

            string[] filePaths = Directory.GetFiles(workingDirectory);
        }
        static void Main(string[] args)
        {
            listFilesInDirectory(@"C:\Temp");
            foreach (string filePath in filePaths)
            {
                Console.WriteLine(filePath);
            }
        }
    }

asked 2 months ago

Correct Answer

In this case you cannot access filePaths because it's out of the scope of the method, there are 2 ways you can solve the problem: you either declare a static variable within the class, so that any method can access it, or you make listFilesInDirectory return a string[].

1st method:

internal class Program
{
    private static string[] filePaths;

    static void listFilesInDirectory(string workingDirectory)
    {
        // Let's find some files
       filePaths = Directory.GetFiles(workingDirectory);
    }
    static void Main(string[] args)
    {
        // Receive the return from listFilesInDirectory();
        listFilesInDirectory(@"C:\Temp");
        foreach (string filePath in filePaths)
        {
            Console.WriteLine(filePath);
        }
    }
}

(Note that this method will overwrite the filePaths variable every time you call listFilesInDirectory)

2nd method:

internal class Program
{
    static string[] listFilesInDirectory(string workingDirectory)
    {
        // Let's find some files
        return filePaths = Directory.GetFiles(workingDirectory);
    }

    static void Main(string[] args)
    {
        string[] filePaths = listFilesInDirectory(@"C:\Temp");
        foreach (string filePath in filePaths)
        {
            Console.WriteLine(filePath);
        }
    }
}

I'd suggest you use the second method, because it's cleaner, more readable and less errore prone

answered 2 months ago

Other Answer

You're attempting to access something out of scope and fail to return the output of the Directory.GetFiles. What you would want to do would be along the following:

public class Startup
{
     public static void Main(string[] arguments)
     {
           var files = GetFilesFromPath("Location Here");
           foreach(var file in files)
                Console.WriteLine(file);
     }

     public IEnumerable<string> GetFilesFromPath(string path) => Directory.GetFiles(path);
}

The code will have potential errors, but the point would be the lambda will return the files. Then inside the main you do a variable with those values, then you can iterate through them.

answered 2 months ago