我需要访问网络路径

时间:2011-05-02 20:34:13

标签: c# windows unc

我有一个Windows服务,并试图使用pinvoke映射它。代码在控制台应用程序中工作正常,但它在Windows服务中没有任何效果。根据这个:

"net use" command in a Windows Service

我应该删除net use方法,而是提供适当的权限,以便我的服务可以访问UNC路径(\ server \ share \ file-path)。如何设置这些权限?我认为应该在某处设置基本的Windows权限。任何帮助表示赞赏。

[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;
}

和......

       static void Main()
        {
            USE_INFO_2 useInfo = new USE_INFO_2();
            useInfo.ui2_remote = @"\\xx.xx.xx.xx\E$"; // "\\xx.xx.xx.xx\E$"
            useInfo.ui2_password = "********";
            useInfo.ui2_asg_type = 0;    //disk drive
            useInfo.ui2_usecount = 1;
            useInfo.ui2_username = "Admin";
            useInfo.ui2_domainname = "rendering";
            uint paramErrorIndex;
            uint returnCode = NetUseAdd(String.Empty, 2, ref useInfo, out paramErrorIndex);
            if (returnCode != 0)
            {
                throw new Win32Exception((int)returnCode);
            }
...

1 个答案:

答案 0 :(得分:1)

您可以将Windows服务作为可以访问此路径的域/ Windows用户启动。