Reputation: 1147
I want to change this label:
In the above picture I changed it manually without any permissions.
I tryed the following as said in this thread but it gives an System.UnauthorizedAccessException
public void setVolumeLabel(String oldName, string newLabel){
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives){
if (d.IsReady && d.Name.Equals(oldName)){
d.VolumeLabel = newLabel;
}
}
So the VolumeLabel property is not what I'm looking for. Then I read this post, but can't import the Shell32.dll for some reason, it says Axlmp.exe cannpt be found.
Tried also with SetVolumeName(). It returns nonzero numbers, but doesn't change de VolumeName.
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool SetVolumeLabel(String letter, String label);
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
Upvotes: 0
Views: 1021
Reputation: 244752
As the documentation for the DriveInfo.VolumeLabel
property states very clearly, an UnauthorizedAccessException
can be thrown for one of the following reasons:
- The volume label is being set on a network or CD-ROM drive.
- Access to the drive information is denied.
The second one was a good assumption; it is the one that LordWilmore made in his answer. However, you've indicated that is not the case.
This leaves the first one, which makes sense, considering you've indicated in a comment to the question that drive J: is, in fact, a network drive. You cannot use this mechanism to change the label of a network drive.
To do this, you need to use a COM interface. You will query the shell to obtain a Folder2
object representing the network drive you wish to manipulate. Then, you will use this object's Self
property to retrieve the folder's corresponding FolderItem
object. Finally, you can directly set the Name
property for that object.
Here is the solution in C++, and you already found the solution in C# and VB 6. However, you claim that you were unable to add a reference to the "Microsoft Shell Controls and Automation" library as Syberdoor suggested. I'm not sure why not. The error message you're getting makes very little sense. AxImp.exe is part of the standard .NET Framework install. You are possibly doing it wrong. Try:
I guess if you somehow do not have the Windows SDK installed, you could be missing AxImp.exe, and Visual Studio could be failing to create the stub assembly that allows you to use the typelib. I cannot imagine how that could possibly happen. If you have Visual Studio installed, you should have gotten the SDK.
Upvotes: 0
Reputation: 2912
As you are (presumably) logged in with administrator rights you can edit this from within Explorer. But your C# software does not run as administrator unless you specifically say so by one of the following methods:
1) Running VS as administrator
2) Run your application from within Explorer as administrator
3) Configure your application to run as administrator through its manifest
Upvotes: 1