Question

My program needs to read and write to folders on other machines that might be in another domain. So I used the System.Runtime.InteropServices to add shared folders. This worked fine when it was hard coded in the main menu of my windows service. But since then something went wrong and I don't know if it is a coding error or configuration error.

  • What is the scope of a shared folder? If a thread in my program adds a shared folder, can the entire local machine see it?
  • Is there a way to view what shared folders has been added? Or is there a way to see when a folder is added?

    [DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern System.UInt32 NetUseAdd(string UncServerName, int Level, ref USE_INFO_2 Buf, out uint ParmError);
    
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    internal struct USE_INFO_2
    {
        internal LPWSTR ui2_local;
        internal LPWSTR ui2_remote;
        internal LPWSTR ui2_password;
        internal DWORD ui2_status;
        internal DWORD ui2_asg_type;
        internal DWORD ui2_refcount;
        internal DWORD ui2_usecount;
        internal LPWSTR ui2_username;
        internal LPWSTR ui2_domainname;
    }
    
    private void AddSharedFolder(string name, string domain, string username, string password)
    {
        if (name == null || domain == null || username == null || password == null)
            return;
    
        USE_INFO_2 useInfo = new USE_INFO_2();
        useInfo.ui2_remote = name;
        useInfo.ui2_password = password;
        useInfo.ui2_asg_type = 0;    //disk drive
        useInfo.ui2_usecount = 1;
        useInfo.ui2_username = username;
        useInfo.ui2_domainname = domain;
        uint paramErrorIndex;
        uint returnCode = NetUseAdd(String.Empty, 2, ref useInfo, out paramErrorIndex);
        if (returnCode != 0)
        {
            throw new Win32Exception((int)returnCode);
        }
    }
    
Was it helpful?

Solution

Each thread in a computer runs under a specific user account. Shared folder have security settings, i.e. they are subject to ACL-based access control, so that some users may have access permission and others may not. This means that the thread in your program may be able to "see" some shared folders, while other threads in the same computer (including the interactive user using the desktop) might be unable to "see" those folders.

In summary: you should assume very little.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top