2009-10-22

Windows Services and the Network

Let's make this very clear: a service should not use or change drive mappings at all. See KB180362 (INFO: Services and Redirected Drives) (webcite) and Services and Redirected Drives (MSDN) (webcite) for more information. If a service needs to use network resources, it should use UNC paths.

Network drive mappings are handled differently on different Windows versions. In addition, network drive mappings are one type of an "MS-DOS Device Name", so they fall under the additional complications described in Local and Global MS-DOS Device Names (webcite).

Note that a service running as LocalService (webcite) uses anonymous credentials to access network resources, and services running as NetworkService (webcite) or LocalSystem (webcite) use machine account credentials.

2 comments:

  1. hi cleary this is suresh

    Windowservice
    -----------------------

    private System.Timers.Timer timer;
    protected override void OnStart(string[] args)
    {
    this.timer = new System.Timers.Timer(20000); // 30000 milliseconds = 30 seconds
    this.timer.AutoReset = true;
    this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
    this.timer.Start();
    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
    EventLog log = new EventLog();
    log.Source = "suresh";
    string pathvalue = Pathing.GetUNCPath(Clipboard.GetText());
    if (pathvalue != "")
    {
    log.WriteEntry(pathvalue);
    }
    }

    public static class Pathing
    {
    [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern int WNetGetConnection(
    [MarshalAs(UnmanagedType.LPTStr)] string localName,
    [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
    ref int length);
    public static string GetUNCPath(string originalPath)
    {
    StringBuilder sb = new StringBuilder(512);
    int size = sb.Capacity;
    if (originalPath.Length > 2 && originalPath[1] == ':')
    {
    char c = originalPath[0];
    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
    {
    int error = WNetGetConnection(originalPath.Substring(0, 2),
    sb, ref size);
    if (error == 0)
    {
    DirectoryInfo dir = new DirectoryInfo(originalPath);

    string path = Path.GetFullPath(originalPath)
    .Substring(Path.GetPathRoot(originalPath).Length);
    return Path.Combine(sb.ToString().TrimEnd(), path);
    }
    }
    }

    return originalPath;
    }
    }

    Please tel me any wrang in code

    ReplyDelete
    Replies
    1. As I explain in this blog post, Win32 services are not supposed to use network connections. They can use UNC paths, but you have to do that kind of translation in an application running in the user's desktop. If you have a tray or background application translate the network drive to a UNC path, then it can pass the UNC path to the Win32 service. But the service itself cannot do that translation.

      Delete