简体   繁体   中英

How to Programmatically Map Drive for SQL Server Session

How can a drive (eg y) be mapped in C# to a network shared location? The mapped drive needs to be known by a SQL session. This is for backing up SQL databases from a C# application to the mapped drive (eg y). Would like to do it programmatically to allow easily changing the mapped drive network location, user and password.

Within SSMS / SQL session, I could create a mapped drive in a query window:

EXEC xp_cmdshell 'net use y: \\host11\special\temp temppassword /user:host11\sphr /persistent:no'

I could then backup the SQL Server databases from the C# application. Wondering, how do I do this in C#?

The C#/.Net equivalent of MSSQL "EXEC xp_cmdshell" is Process.Start() .

I thought you might also be able to do it with WMI, but it looks like that's not really practical for this use case:

Querying access to a UNC path on a remote machine via WMI

NOTE:

One problem I recall is that, when the MSSQL service runs in the context of "LocalSystem", you cannot access any network resources (like disk shares). Here are some workarounds:

How to grant network access to LocalSystem account?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM