473,387 Members | 1,569 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 11488

"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
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
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
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
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
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
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
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
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
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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...

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.