1

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

TH3SN3R
  • 47
  • 9
  • 1
    You’re trying to give the path to the `GetFiles` in the second snippet, which causes the issue. You don’t have it in the first one. Remove that parameter. – Sami Kuhmonen Sep 24 '17 at 12:39
  • @SamiKuhmonen Thank you very much for pointing that out. I have been sitting here for about an hour trying to figure it out. A fresh pair of eyes always help. Thanks for correcting my idiocy – TH3SN3R Sep 24 '17 at 12:44

1 Answers1

1

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();
    }
Kevin Ford
  • 260
  • 1
  • 7