Pergunta

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"

        }
    }
Foi útil?

Solução

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);

Outras dicas

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"))

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top