Click here to Skip to main content
15,887,343 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
DriveInfo drive =(DriveInfo)lstdrive.SelectedItem;
foreach (DriveInfo diInfo in drive.RootDirectory.GetDirectories())
{
    lstfolder.Items.Add(diInfo.ToString());
}


What I have tried:

DriveInfo drive =(DriveInfo)lstdrive.SelectedItem.tostring();
Posted
Updated 13-May-16 22:09pm
v2
Comments
Sergey Alexandrovich Kryukov 13-May-16 23:32pm    
Read carefully: Unhappy Inquirer or Is the Abuse the Main Purpose of Programming?
Are you getting the idea?
—SA
Karthik_Mahalingam 14-May-16 3:14am    
Wrong way of coding, Not encouraged to provide solution for this.
tell us what you want to achieve, we can help on that..

1 solution

Um...look at what you are doing:
C#
foreach (DriveInfo diInfo in drive.RootDirectory.GetDirectories())
{
    lstfolder.Items.Add(diInfo.ToString());
}
So each item you add to the ListView is a string, not a DriveInfo.
So when you try to cast it back to a driveinfo:
C#
DriveInfo drive =(DriveInfo)lstdrive.SelectedItem.tostring();
You have a number of problems:
First, the use of ToString on the SelectedItem turns it into a string, so regardless of what type the ListView contained, it can't be cast to anything except a string or a class derived from a string - and since string is a sealed class nothing can be derived from it. So this code:
C#
AnyClassOtherThanStringOrObject x = (AnyClassOtherThanStringOrObject) anyValue.ToString();
will always fail.

Secondly, since you converted it to a string when you inserted it to the listview, you will still have exactly the same problem if you remove the ToString call from SelectedItem - as what the item value is, is an instance of a string!

Probably what you need to do is store the DriveInfo directly into the ListView, and directly cast it back to a DriveInfo when you retrieve the SelectedItem ... but ...

Thirdly, this is web based, so you should be aware that in production that code is in all probability still not going to work! The C# code executes on the Server, not the Client, so the root directory it scans is the Server root, not the Client - it appears to work when you test it because they are the same machine. But in production, the Server may be several thousand KM from the Client, and exposing the Server disk is a horrible security risk!
Your code cannot access the Client harddrive directly - and you should be glad of that. Because if you could do it, so could malicious sites...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900