0

I'm using a code to show all startup items in listbox with environment variable "%appdata% There is some errors in this code that I need help with.... Check code for commented errors

Is there any other solution but still using %appdata%?

This is the code:

    private void readfiles()
    {
        String startfolder = Environment.ExpandEnvironmentVariables("%appdata%") + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
        foldertoread(startfolder);
    }

    private void foldertoread(string folderName)
    {
        FileInfo[] Files = folderName.GetFiles("*.txt"); // HERE is one error "Getfiles"
        foreach (var file in Directory.GetFiles(folderName))
        {
            startupinfo.Items.Add(file.Name); // here is another error "Name"

        }
    }
Sneakybastardd
  • 288
  • 1
  • 5
  • 17
  • 1
    In the future, don't just say you "have an error". It's good you pointed out what line it's on, but knowing **what the error is** is useful to those trying to help you. In this case, it's fairly obvious, but otherwise it might not. – tnw Apr 10 '13 at 19:35

3 Answers3

2

This line won't work because folderName is a string (and does not have a GetFiles method):

FileInfo[] Files = folderName.GetFiles("*.txt");

The second error is occurring because the file variable is a string containing the filename. You don't need to call file.Name, just try the following:

startupinfo.Items.Add(file);
Martin
  • 16,093
  • 1
  • 29
  • 48
  • The problem why I want "name" is that I only want to show the names, not the whole location+filename.extension Another solution for that is ofcourse appreciated! When I changed as you said i got this error.. Cannot implicitly convert type 'string[]' to 'System.IO.FileInfo[]' on this line: FileInfo[] Files = folderName.GetFiles("*.txt"); – Sneakybastardd Apr 10 '13 at 19:36
  • Just use `Path.GetFileNameWithoutExtension()` on the `file` variable, like so: `startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));` – Martin Apr 10 '13 at 19:37
0

I don't think you need the following line:

FileInfo[] Files = folderName.GetFiles("*.txt");

The foreach loop will generate what you need. Secondly, the file variable is a string, so rather than calling:

startupinfo.Items.Add(file.Name);

...call instead:

startupinfo.Items.Add(file);

Finally, instead of a var type for your loop, you can use a string, and you can specify the file type filter:

foreach (string fileName in Directory.GetFiles(folderName, "*.txt"))
Geoff
  • 8,551
  • 1
  • 43
  • 50
0

The string object doesn't have a GetFiles() method. Try this:

string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

string[] files = Directory.GetFiles(startfolder, "*.txt");

foreach (string file in files)
{
   startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
}

Path.GetFileNameWithoutExtension(file) returns just the file name instead of full path.

Arian Motamedi
  • 7,123
  • 10
  • 42
  • 82