TH3SN3R TH3SN3R - 25 days ago 12
C# Question

GetFiles() error with user input path

I am trying to get all files in a directory, from a path gotten from user input in the console. But I keep getting this error 'System.ArgumentException: 'Second path fragment must not be a drive or UNC name' I Have looked at this Second path fragment must not be a drive or UNC name - Create Subdirectory Error answer, which says the error is because of the drive name in the path, but that doesnt make sense. When I test the code like this it works when the path is hardcoded WITH the drive letter.

DirectoryInfo d = new DirectoryInfo(@"C:\Users\Christopher Thesner\Desktop\Spoon\");
dir = d.GetDirectories();
files = d.GetFiles();


But when I try it like this, where the path is stored in a variable from user input, it throws an error.

DirectoryInfo d = new DirectoryInfo(path);
dir = d.GetDirectories();
files = d.GetFiles(path);


I have tried to get the directory name from the string as a path like this

directory = Path.GetDirectoryName(directory);


as suggested here as well Second path fragment must not be a drive or UNC name - Create Subdirectory Error but no look. Any ideas? Thanks in advance

Answer Source

Simple example:

    private void Form1_Load(object sender, EventArgs e)
    {
        var path = Environment.CurrentDirectory;
        List<String> lines = new List<string>();
        DirectoryInfo d = new DirectoryInfo(path);
        var dir = d.GetDirectories();
        var files = d.GetFiles();
        lines.Add(String.Format("There are {0} directories in \"{1}\"", dir.Length, d.Name));
        lines.Add(String.Format("There are {0} files in \"{1}", files.Length, d.Name));
        foreach (var di in dir)
        {
            lines.Add(String.Format("There are {0} directories in \"{1}\"", dir.Length, d.Name));
            files = di.GetFiles();
            lines.Add(String.Format("There are {0} files in \"{1}", files.Length, d.Name));
        }
        textBox1.Lines = lines.ToArray();
    }