[ACCEPTED]-How do I access a file share programmatically-file-sharing
You can use WNetAddConnection to accomplish 8 this. You will have to pInvoke. the code 7 below worked for me after I set up the pInvoke 6 declarations. The second block of code 5 (below) contains the pInvoke declarations 4 -- just stick it inside of a class.
public static void CopyFile(string from, string shareName, string username, string password)
{
NETRESOURCE nr = new NETRESOURCE();
nr.dwType = ResourceType.RESOURCETYPE_DISK;
nr.lpLocalName = null;
nr.lpRemoteName = shareName;
nr.lpProvider = null;
int result = WNetAddConnection2(nr, password, username, 0);
System.IO.File.Copy(from, System.IO.Path.Combine(shareName, System.IO.Path.GetFileName(from)));
}
You will 3 need to paste the following supporting code 2 into a class (taken from pInvoke.Net). Make 1 sure to add a using statment to your code:
using System.Runtime.InteropServices
[DllImport("Mpr.dll", EntryPoint = "WNetAddConnection2", CallingConvention = CallingConvention.Winapi)]
private static extern int WNetAddConnection2(NETRESOURCE lpNetResource, string lpPassword,
string lpUsername, System.UInt32 dwFlags);
[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public ResourceScope dwScope = 0;
public ResourceType dwType = 0;
public ResourceDisplayType dwDisplayType = 0;
public ResourceUsage dwUsage = 0;
public string lpLocalName = null;
public string lpRemoteName = null;
public string lpComment = null;
public string lpProvider = null;
};
public enum ResourceScope
{
RESOURCE_CONNECTED = 1,
RESOURCE_GLOBALNET,
RESOURCE_REMEMBERED,
RESOURCE_RECENT,
RESOURCE_CONTEXT
};
public enum ResourceType
{
RESOURCETYPE_ANY,
RESOURCETYPE_DISK,
RESOURCETYPE_PRINT,
RESOURCETYPE_RESERVED
};
public enum ResourceUsage
{
RESOURCEUSAGE_CONNECTABLE = 0x00000001,
RESOURCEUSAGE_CONTAINER = 0x00000002,
RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
RESOURCEUSAGE_SIBLING = 0x00000008,
RESOURCEUSAGE_ATTACHED = 0x00000010,
RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
};
public enum ResourceDisplayType
{
RESOURCEDISPLAYTYPE_GENERIC,
RESOURCEDISPLAYTYPE_DOMAIN,
RESOURCEDISPLAYTYPE_SERVER,
RESOURCEDISPLAYTYPE_SHARE,
RESOURCEDISPLAYTYPE_FILE,
RESOURCEDISPLAYTYPE_GROUP,
RESOURCEDISPLAYTYPE_NETWORK,
RESOURCEDISPLAYTYPE_ROOT,
RESOURCEDISPLAYTYPE_SHAREADMIN,
RESOURCEDISPLAYTYPE_DIRECTORY,
RESOURCEDISPLAYTYPE_TREE,
RESOURCEDISPLAYTYPE_NDSCONTAINER
};
The accepted answer on this question here seems 7 like it would be worth looking into; it 6 suggests using the Win32 API function WNetUseConnection.
From 5 MSDN:
The WNetUseConnection function makes a connection 4 to a network resource. The function can 3 redirect a local device to a network resource.
Which 2 seems to accomplish what you're looking 1 for, with no mention of net.exe
. Does this help?
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.