0

How can a drive (e.g. 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 (e.g. 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#?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Buck
  • 599
  • 7
  • 20
  • 2
    Please don't just ask us to solve the problem for you. Show us how _you_ tried to solve the problem yourself, then show us _exactly_ what the result was, and tell us why you feel it didn't work. See "[What Have You Tried?](http://whathaveyoutried.com/)" for an excellent article that you _really need to read_. – John Saunders May 08 '15 at 03:20
  • Look at `Process.Start()` – Eric J. May 08 '15 at 03:23
  • 1
    Can't you backup locally then copy to a UNC? Then you don't need to map a drive (which is fraught with complications, especially if you want to make the SQL Server 'see' a drive mapped by something else). If you must do it, what's to stop you submitting that drive mapping SQL from your C# application? – Nick.Mc May 08 '15 at 03:30
  • Nick, I can make your "copy to a UNC" solution work. Perfect and thanks! – Buck May 08 '15 at 03:38
  • Thanks John! I will look to do that next time. – Buck May 08 '15 at 03:42

1 Answers1

1

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?

Community
  • 1
  • 1
FoggyDay
  • 11,962
  • 4
  • 34
  • 48
  • I think the tricky part is getting C# to map a drive in the same session as SQL Server is running. – Gabe May 08 '15 at 05:00