Reputation:
I have created a Windows Service that runs under a domain user that has (administrator) rights to all network sources.
At the start of the Windows Service I have included the following code:
My.User.InitializeWithWindowsUser()
If I use IO.DriveInfo.GetDrives to get a collection of all drives, then the result is only a collection of local drives, not network drives (drive mappings).
What am I missing here?
NB: Although I use VB.NET I understand/know also C#, so that's why I tagged this question also with C#. So C# example are also welcome.
Upvotes: 0
Views: 1068
Reputation: 3685
This is because of a misunderstanding. as noted in MSDN, My.User.InitializeWithWindowsUser()
only sets current thread's principals. Your thread only impersonates user. It DOES NOT connect to the user session where network mappings are stored.
To access mapped drives of a user you need to access currently logged on user's desktop session which is meaningless since there may be no user logged on.
To make fun, I had one written a windows service which spans an executable in logged on user's windows session as user launched it, and connect to the outlook and send mail to whole company "Hey, desserts for everybody, my treat!".
This is what you are looking for.
Upvotes: 0
Reputation: 14682
It is going to depend on at what point those drives are mapped. For example, it is possible that your drive mappings are set up via a login script that is not being run.
If this is the case, you can either reference the drives via UNC path, or map them yourself first, this kind of thing:
http://www.blackwasp.co.uk/MapDriveLetter.aspx
Upvotes: 2
Reputation: 5808
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo di in drives)
{
if (di.IsReady)
{
Console.WriteLine("Volume label: {0} ", di.VolumeLabel);
Console.WriteLine("Drive Type: {0} ", di.DriveType);
Console.WriteLine("Free space: {0} bytes ", di.TotalFreeSpace);
Console.WriteLine("Drive Size: {0} bytes \n", di.TotalSize);
}
}
Console.ReadLine();
}
catch (Exception ex)
{
// handle ex
}
}
}
}
I have just tried this and it gets all the drives including network. Hope it helps.
Upvotes: 0