473,503 Members | 11,237 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Service - authenticating to a network fileshare?

I have a C# service (running as Network Service account) that needs to
access a fileshare:
\\machinename\some\path

This file share requires me to login with certain credentials. How can I
specify these from the context of my application?

Thanks!

--
Adam Clauss

Nov 17 '05 #1
4 11506

"Adam Clauss" <ca*****@tamu.edu> wrote in message
news:11*************@corp.supernews.com...
I have a C# service (running as Network Service account) that needs to
access a fileshare:
\\machinename\some\path

This file share requires me to login with certain credentials. How can I
specify these from the context of my application?

Thanks!

--
Adam Clauss


You have several options depending on the context.
If you are running on a member server in a AD domain, you can simply add the
"computer" name of the server running te service to the ACL of the shared
directory on the resource server.
Another option requires some PInvoke interop, you have to create a new logon
session token (by calling LogonUser()) in the service and use the obtained
token to impersonate the caller when accessing the remote resource.
Yet another option is to establish a "use record" from within the service by
calling Win32's API "NetUseAdd", following is a sample that illustrates this
last option.

[StructLayout(LayoutKind.Sequential,CharSet=CharSet .Auto)]
struct _USE_INFO_2
{
internal string ui2_local;
internal string ui2_remote;
internal IntPtr ui2_password; // don't pass a string or StringBuilder
here!!
internal uint ui2_status;
internal uint ui2_asg_type;
internal uint ui2_refcount;
internal uint ui2_usecount;
internal string ui2_username;
internal string ui2_domainname;
}
class WinNet
{
[DllImport("netapi32", CharSet=CharSet.Auto, SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern int NetUseAdd(
string UncServerName, // not used
int Level, // use info struct level 1 or 2
IntPtr Buf, // Buffer
ref int ParmError
);
const uint USE_WILDCARD = 0xFFFFFFFF;

// Establish a use record
public static void UseRecord(string resource, string user, string
password, string domain)
{
int ret = 0;
int paramError = 0;
_USE_INFO_2 use2 = new _USE_INFO_2();
IntPtr pBuf = IntPtr.Zero;
use2.ui2_password = IntPtr.Zero;
try
{
pBuf = Marshal.AllocHGlobal(Marshal.SizeOf(use2));
use2.ui2_local = null;
use2.ui2_asg_type = USE_WILDCARD;
use2.ui2_remote = resource;
use2.ui2_password = Marshal.StringToHGlobalAuto(password);
use2.ui2_username = user;
use2.ui2_domainname = domain;
Marshal.StructureToPtr(use2, pBuf, true);
ret = NetUseAdd(null, 2, pBuf, ref paramError);
if(ret != 0)
{
throw new Exception(new
Win32Exception(Marshal.GetLastWin32Error()).Messag e);
}
}
finally
{
Marshal.FreeHGlobal(use2.ui2_password);
Marshal.FreeHGlobal(pBuf);
}
}
}

//usage...
WinNet.UseRecord("\\\\servername\\share", "useraccount", "hispasswd",
"domainname");

Note that it's recommended to delete the session, by calling NetUseDel(),
when you are done with it.
Willy.
Nov 17 '05 #2

Użytkownik "Adam Clauss" <ca*****@tamu.edu> napisał w wiadomo¶ci
news:11*************@corp.supernews.com...
I have a C# service (running as Network Service account) that needs to
access a fileshare:
\\machinename\some\path

This file share requires me to login with certain credentials. How can I
specify these from the context of my application?

Thanks!

--
Adam Clauss


Hey, did you find and solve for that? I am looking for that too.
Nov 17 '05 #3
Check out the other reply to my message.

--
Adam Clauss

"Inez Korczynski" <ko*************@gazeta.pl> wrote in message
news:da**********@inews.gazeta.pl...

Użytkownik "Adam Clauss" <ca*****@tamu.edu> napisał w wiadomo¶ci
news:11*************@corp.supernews.com...
I have a C# service (running as Network Service account) that needs to
access a fileshare:
\\machinename\some\path

This file share requires me to login with certain credentials. How can I
specify these from the context of my application?

Thanks!

--
Adam Clauss


Hey, did you find and solve for that? I am looking for that too.

Nov 17 '05 #4
Thanks!

--
Adam Clauss

"Willy Denoyette [MVP]" <wi*************@telenet.be> wrote in message
news:uE*************@TK2MSFTNGP09.phx.gbl...

"Adam Clauss" <ca*****@tamu.edu> wrote in message
news:11*************@corp.supernews.com...
I have a C# service (running as Network Service account) that needs to
access a fileshare:
\\machinename\some\path

This file share requires me to login with certain credentials. How can I
specify these from the context of my application?

Thanks!

--
Adam Clauss


You have several options depending on the context.
If you are running on a member server in a AD domain, you can simply add
the "computer" name of the server running te service to the ACL of the
shared directory on the resource server.
Another option requires some PInvoke interop, you have to create a new
logon session token (by calling LogonUser()) in the service and use the
obtained token to impersonate the caller when accessing the remote
resource.
Yet another option is to establish a "use record" from within the service
by calling Win32's API "NetUseAdd", following is a sample that illustrates
this last option.

[StructLayout(LayoutKind.Sequential,CharSet=CharSet .Auto)]
struct _USE_INFO_2
{
internal string ui2_local;
internal string ui2_remote;
internal IntPtr ui2_password; // don't pass a string or StringBuilder
here!!
internal uint ui2_status;
internal uint ui2_asg_type;
internal uint ui2_refcount;
internal uint ui2_usecount;
internal string ui2_username;
internal string ui2_domainname;
}
class WinNet
{
[DllImport("netapi32", CharSet=CharSet.Auto, SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern int NetUseAdd(
string UncServerName, // not used
int Level, // use info struct level 1 or 2
IntPtr Buf, // Buffer
ref int ParmError
);
const uint USE_WILDCARD = 0xFFFFFFFF;

// Establish a use record
public static void UseRecord(string resource, string user, string
password, string domain)
{
int ret = 0;
int paramError = 0;
_USE_INFO_2 use2 = new _USE_INFO_2();
IntPtr pBuf = IntPtr.Zero;
use2.ui2_password = IntPtr.Zero;
try
{
pBuf = Marshal.AllocHGlobal(Marshal.SizeOf(use2));
use2.ui2_local = null;
use2.ui2_asg_type = USE_WILDCARD;
use2.ui2_remote = resource;
use2.ui2_password = Marshal.StringToHGlobalAuto(password);
use2.ui2_username = user;
use2.ui2_domainname = domain;
Marshal.StructureToPtr(use2, pBuf, true);
ret = NetUseAdd(null, 2, pBuf, ref paramError);
if(ret != 0)
{
throw new Exception(new
Win32Exception(Marshal.GetLastWin32Error()).Messag e);
}
}
finally
{
Marshal.FreeHGlobal(use2.ui2_password);
Marshal.FreeHGlobal(pBuf);
}
}
}

//usage...
WinNet.UseRecord("\\\\servername\\share", "useraccount", "hispasswd",
"domainname");

Note that it's recommended to delete the session, by calling NetUseDel(),
when you are done with it.
Willy.

Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2380
by: Daniel Xiao | last post by:
I write a program accessing files in network drive o:. It is doable as a standalone application. However, if it is running under windows service, the following exception will appear: 13/07/2004...
3
7614
by: Daniel Xiao | last post by:
I write a program accessing files in network drive o:. It is doable as a standalone application. However, if it is running under windows service, the following exception will appear: 13/07/2004...
13
491
by: J | last post by:
I create a windows application to delete old data in sql server without any problem. Then I create a windows service to handle this task due to this task is a daily basis job. I also have let this...
3
2228
by: todd_groten | last post by:
Alright, I've been searching around for some time and have not been able to find anything concrete on fixing an issue I am having. Here's the situation: 1) I have a non-anonymous webservice...
5
4445
by: Nirosh | last post by:
Hi All, Can any one suggest me a best way to do this .. I have a thrid party tool "EXE" that we need to use with our web service to manipulate some complex XML files, which reside in a...
0
1246
by: Chris | last post by:
Hello, I have writen a windows service accessing files on a shared network drive. I configured the service running under a network account which can access the network share. But, when my...
1
1634
by: GM | last post by:
Hello, I need ideas, concepts to realize the following things: I have a service (vb.net) running on a workstation communicating with a client application. The data flow does not need to be...
3
7722
by: Brad | last post by:
I'm setting up my new pc with all my VS.net projects and I'm missing something.....something I've done many times before without problem. I have several asp.net apps accessing secure .net web...
3
9181
by: BLUE | last post by:
I've created a folder named TestDir in my wwwroot and I've created the associated virtual application from IIS management snap-in. I've given full control to TestDir to: IUSR, ASPNET, Network...
0
7194
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7070
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
6976
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7449
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5566
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3160
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3148
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1495
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
372
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.