How to update a Treeview of C#directories

Asked

Viewed 318 times

2

I have a Treeviewms component (the one with Multiple Selection) listing the system directories in a Form.

I created an event on the Form that when F5 is pressed, this Treeview will update itself(if you have any new directory on the system or not).

He even gets to upgrade normally, then is thrown a NullReferenceException in Treeview MS.dll in the initial class of the program (Program.Cs)

follows code to load the Treeview.

private void LoadTreeView() {
   tvDirectories.Nodes.Clear();
   exArq.CreateDirectoryTree(tvDirectories);
}

this is the Exception:

An unhandled exception of type 'System.NullReferenceException' occurred in TreeViewMS.dll Additional information: Referência de objeto não definida para uma instância de um objeto.

Method Createdirectorytree searches the system directories and mounts the tree, I believe it is not the problem but follows the method:

public TreeViewMS.TreeViewMS CreateDirectoryTree(TreeViewMS.TreeViewMS treeView) {

    foreach (DriveInfo drv in DriveInfo.GetDrives()) {
        TreeNode rootDirectoryNode = new TreeNode();
        rootDirectoryNode.ImageIndex = ImageIndexs.SystemDiskIcon;
        rootDirectoryNode.SelectedImageIndex = ImageIndexs.SystemDiskIcon;
        rootDirectoryNode.Text = drv.Name;

        switch (drv.DriveType) {

            case DriveType.Network:
                rootDirectoryNode.ImageIndex = ImageIndexs.NetworkDiskIcon;
                rootDirectoryNode.SelectedImageIndex = ImageIndexs.NetworkDiskIcon;
                break;

            case DriveType.CDRom:
                rootDirectoryNode.ImageIndex = ImageIndexs.CDDiskIcon;
                rootDirectoryNode.SelectedImageIndex = ImageIndexs.CDDiskIcon;
                break;

            case DriveType.Fixed:
                rootDirectoryNode.ImageIndex = ImageIndexs.LocalDiskIcon;
                rootDirectoryNode.SelectedImageIndex = ImageIndexs.LocalDiskIcon;
                break;

            case DriveType.Removable:
                rootDirectoryNode.ImageIndex = ImageIndexs.RemovalDiskIcon;
                rootDirectoryNode.SelectedImageIndex = ImageIndexs.RemovalDiskIcon;
                break;

        }

        bool isSystemDirectory = drv.Name.ToString() == Path.GetPathRoot(Environment.SystemDirectory);

        if (isSystemDirectory) {
            rootDirectoryNode.ImageIndex = ImageIndexs.SystemDiskIcon;
            rootDirectoryNode.SelectedImageIndex = ImageIndexs.SystemDiskIcon;
        }

        rootDirectoryNode.Nodes.Add(String.Empty);

        treeView.Nodes.Add(rootDirectoryNode);
    }
    return treeView;

}        

I suspect it is the way to clean up Treeview that must be causing the error.

I imagine it shouldn’t be, but I’ll also include where the knot is expanded:

private void tvDiretorios2_BeforeExpand(object sender, TreeViewCancelEventArgs e) {
     TreeNode newNode = exArq.GetDirectoriesAndFilesNodes(e.Node);
}

and the function that seeks these directories

public TreeNode GetDirectoriesAndFilesNodes(TreeNode parentNode) {

    string nodePath = parentNode.FullPath + Constants.DIRECTORY_SEPARATOR;

    DirectoryInfo rootDirectory = new DirectoryInfo(nodePath);
    parentNode.Nodes[0].Remove();
    try {

        foreach (DirectoryInfo dir in rootDirectory.GetDirectories()) {

            TreeNode directoryNode = new TreeNode();
            directoryNode.Text = dir.Name;
            directoryNode.Nodes.Add(String.Empty);
            directoryNode.ImageIndex = ImageIndexs.DirectoryIcon;
            directoryNode.SelectedImageIndex = ImageIndexs.DirectoryIcon;
            parentNode.Nodes.Add(directoryNode);

        }

        foreach (FileInfo file in rootDirectory.GetFiles()) {

            bool isExcel = Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_EXCEL_X) || Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_EXCEL);

            bool isZipedFile = Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_RAR) || Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_ZIP);

            bool isTextFile = Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_TXT);

            TreeNode fileNode = new TreeNode();
            fileNode.Text = file.Name;

            if (isExcel) {
                fileNode.ImageIndex = ImageIndexs.ExcelFileIcon;
                fileNode.SelectedImageIndex = ImageIndexs.ExcelFileIcon;
            } else if (isZipedFile) {
                fileNode.ImageIndex = ImageIndexs.ZipedFileIcon;
                fileNode.SelectedImageIndex = ImageIndexs.ZipedFileIcon;
            } else if (isTextFile) {
                fileNode.ImageIndex = ImageIndexs.TextFileIcon;
                fileNode.SelectedImageIndex = ImageIndexs.TextFileIcon;
            } else {
                fileNode.ImageIndex = ImageIndexs.GenericFileIcon;
                fileNode.SelectedImageIndex = ImageIndexs.GenericFileIcon;
            }

            parentNode.Nodes.Add(fileNode);
        }

    } catch (UnauthorizedAccessException) {
        TreeNode errorNode = new TreeNode();
        errorNode.Text = "Acesso Negado";
        errorNode.ImageIndex = ImageIndexs.NoPermissionIcon;
        errorNode.SelectedImageIndex = ImageIndexs.NoPermissionIcon;
        parentNode.Nodes.Add(errorNode);
    } catch (IOException) {
        TreeNode errorNode = new TreeNode();
        errorNode.Text = "O Dispositivo não está pronto";
        errorNode.ImageIndex = ImageIndexs.DriverNotReady;
        errorNode.SelectedImageIndex = ImageIndexs.DriverNotReady;
        parentNode.Nodes.Add(errorNode);
    }

    return parentNode;
} 

Thanks to those who can help.

  • 1

    It would be interesting to post the method code BuscarDiretorios.

  • inserted friend @jbueno

  • 1

    I noticed that you cast the derived class Treeviewms back to Treeview. I assume you’re working with this class but, anyway, it would not be better to adapt your methods, as Createdirectorytree() and others, to work with the derivative class Treeviewms guy? I think it’s risky to use the mother class interface, because we might end up using Treeview that were superimposed (overrides) or shaded (Shadows) by specific implementations in Treeviewms.

  • @Vbobcat made the corresponding changes here and updated the question too, thank you for noticing these errors, but it still doesn’t work, in my tests, I access a directory by the program, create a new folder outside it, update Treeview and return to this directory, however, as soon as I create the new folder, Exception is already thrown, before I even update.

  • 1

    Does Exception come at the time when you create the folder via OS? You have in your project some object that monitors changes in directories, for example a Filesystemwatcher?

  • Yes! after creating via operating system. I don’t use Filesystemwatcher (I didn’t even know it), but I can’t imagine where to add it in this situation. Tree is created by Directoryinfo.

  • I believe that without using a Filesystemwatcher, you are not consuming events generated directly by the operating system. At what point exactly do you have the exception? As soon as you create the new folder in Windows Explorer, or when you return to your program and try to use Treeview? If this is the second case, what it seems to me is that the execution begins in the Beforeexpand event handler, and finds some (perhaps internal) object that has become "null". What is the scope of the variable newnode in private void tvDiretorios2_BeforeExpand(object sender, TreeViewCancelEventArgs e)? Why is it defined twice?

  • So, as soon as I get back on the show and Treeview is shown, the exception is thrown. the newNode variable has class scope (the form that uses the Beforeexpand event), I will check if it is used in another method, if it is not, I will leave it inside the Beforeexpand, as to be set twice, I will also check and put an update.

  • updated @Vbobcat however the error persists, but I appreciate your help.

  • 1

    Dear, I don’t work with . NET, but in the Loadtreeview class constructor, are you sure that the tvDirectories and exArq objects are instantiated? When debugging the code, what happens? It seems to be something from control lifecycle (visual object). By the way, you return a Treeview object? It’s kind of weird, because you’re overwriting the instance and references can get totally out of context. Why not just return the node hierarchy and receive the Treeview reference as input? Understand?

  • 1

    After all, it seems to me that this tvDirectories = exArq.Createdirectorytree(tvDirectories); is missing in the constructor. You are returning an instance of Treeview...

Show 6 more comments

1 answer

1

William, to help you identify where the bug is, you can include in your codes a Try...catch, so you can identify where the bug is. Voce can put a breakpoint in the throw.

Using breakpoint you can evaluate the entire exception string and see where the error is.

private void LoadTreeView()
{
    try
    {
        tvDirectories.Nodes.Clear();
        exArq.CreateDirectoryTree(tvDirectories);
    }
    catch (Exception ex)
    {
        throw;
    }
}
  • thanks for the help Alexandre, this function was unnecessary for my system and delivered without it. thanks anyway.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.