Click here to Skip to main content
16,021,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I want to know how can be get access to a shared folder on Server-side using VB6 or C#

I am able to connect to a shared folder on Server-side which is stored in C:\ but what if I want to access the shared folder which is in C:\Program Files\XXXX\SharedFolder

The code for mapping the shared folder in C:\ is as follows: -

There are two different classes.

1. Form.cs

<code>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MapDrive
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
        //Map
        private void btnMap_Click(object sender, EventArgs e)
        {
            NetworkDrive oNetDrive = new NetworkDrive();
            ZUpdateStatus("Mapping Drive...");
            try
            {
                oNetDrive.Force = this.conForce.Checked;
                oNetDrive.LocalDrive = txtDrive.Text;
                oNetDrive.ShareName = txtShareAddr.Text;

                if (txtUser.Text == "" && txtPwd.Text == "")
                    oNetDrive.MapDrive();
                else if (txtUser.Text  == "")
                    oNetDrive.MapDrive(txtPwd.Text);
                else
                    oNetDrive.MapDrive(txtUser.Text, txtPwd.Text);

                ZUpdateStatus("Drive map successful...");

            }
            catch (Exception err)
            {
                ZUpdateStatus("Cannot map drive !!! : " + err.Message);
                MessageBox.Show("Cannot map drive !!!\nError = " + err.Message);
            }
            oNetDrive = null;
        }

        private void ZUpdateStatus(string psStatus)
        {
            this.conStatusBar.Panels[0].Text = psStatus;
            this.Refresh();
        }

        //Unmap
        private void btnUnmap_Click(object sender, EventArgs e)
        {
            NetworkDrive oNetDrive = new NetworkDrive();

            ZUpdateStatus("Unmapping drive...");

            try
            {
                oNetDrive.Force = conForce.Checked;
                oNetDrive.LocalDrive = txtDrive.Text;
                oNetDrive.UnMapDrive();
                ZUpdateStatus("Drive Unmap successful...");
            }
            catch (Exception err)
            {
                ZUpdateStatus("Cannot Unmap Drive !!! - " + err.Message);
                MessageBox.Show("Cannot Unmap Drive !!!\nError = " + err.Message);
            }
        }



    }
}
</code>



2. NetworkDrive.cs


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace MapDrive
{
    class NetworkDrive
    {
        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2A(ref structNetResource pstNetRes, string psPassword, string psUsername, int piFlags);
        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2A(string psName, int piFlags, int pfForce);
        [DllImport("mpr.dll")]
        private static extern int WNetConnectionDialog(int phWnd, int piType);
        [DllImport("mpr.dll")]
        private static extern int WNetDisconnectDialog(int phWnd, int piType);
        [DllImport("mpr.dll")]
        private static extern int WNetRestoreConnectionW(int phWnd, string psLocalDrive);
        [StructLayout(LayoutKind.Sequential)]
        private struct structNetResource
        {
            public int iScope;
            public int iType;
            public int iDisplayType;
            public int iUsage;
            public string sLocalName;
            public string sRemoteName;
            public string sComment;
            public string sProvider;
        }
        private const int RESOURCETYPE_DISK = 0x1;
        //Standard Connections
        //if set OS will interact with user for authentication purposes.
        private const int CONNECT_INTERACTIVE = 0x00000008;
        //the flag isntructs the system not to use any default username or password without
        //offering the user the opportunity to supply an alternative.
        //The flag is ignored unless CONNECT_INTERACTIVE is also set.
        private const int CONNECT_PROMPT = 0x00000010;
        //if this flag is set, the OS automatically attempts to restore connection when the user logs on.
        private const int CONNECT_UPDATE_PROFILE = 0x00000001;
        //This flag forces the redirection of a local device when making the connection
        private const int CONNECT_REDIRECT = 0x00000080;
        //prompts the user for authentication using command and not the GUI
        private const int CONNECT_COMMANDLINE = 0x00000800;
        //prompts for the credential and the credential should be saved by the credential manager.
        private const int CONNECT_CMD_SAVERCD = 0x00001000;
        private  bool if_SaveCredentials = false;
        public bool SaveCredentials
        {
            get { return (if_SaveCredentials); }
            set {if_SaveCredentials=value;}
        }
        private bool if_Persistent = false;
        public bool Persistent
        {
            get {return(if_Persistent);}
            set { if_Persistent = value; }
        }
        private bool if_Force=false;
        public bool Force
        {
            get{return (if_Force);}
            set{if_Force=value;}
        }
        private bool ls_PromptForCredentials = false;
        public bool PrompForCredentials
        {
            get { return (ls_PromptForCredentials); }
            set { ls_PromptForCredentials = value; }
        }
        private string ls_Drive = "s:";
        public string LocalDrive
        {
            get { return ls_Drive; }
            set
            {
                if (value.Length >= 1)
                {
                    ls_Drive = value.Substring(0, 1) + ":";
                }
                else
                {
                    ls_Drive = "";
                }
            }
        }
        private string ls_ShareName = "\\\\Computer\\C$";
        public string ShareName
        {
            get { return ls_ShareName; }
            set { ls_ShareName = value; }
        }
        public void MapDrive() { zMapDrive(null, null); }
        public void MapDrive(string Password) { zMapDrive(null,Password); }
        public void MapDrive(string Username, string Password) { zMapDrive(Username, Password); }
        public void UnMapDrive() { zUnMapDrive (this.if_Force); }
        public void RestoreDrives() { zRestoreDrive(); }
        public void ShowConnectDialog(Form ParentForm) { zDisplayDialog(ParentForm, 1); }
        public void ShowDisconnecDialog(Form ParentForm) { zDisplayDialog(ParentForm, 2); }
        //Core functions:
        private void zMapDrive(string psUsername, string psPassword)
        {
            //create struct data
            structNetResource stNetRes = new structNetResource();
            stNetRes.iScope = 2;
            stNetRes.iType = RESOURCETYPE_DISK;
            stNetRes.iDisplayType = 3;
            stNetRes.iUsage = 1;
            stNetRes.sRemoteName = ls_ShareName;
            stNetRes.sLocalName = ls_Drive;
            //prepare params
            int iFlags = 0;
            //if (lf_SaveCredentials) { iFlags += CONNECT_CMD_SAVECRED; }
            //if (lf_Persistent) { iFlags += CONNECT_UPDATE_PROFILE; }
            if (ls_PromptForCredentials) { iFlags += CONNECT_INTERACTIVE + CONNECT_PROMPT; }
            if (psUsername == "") { psUsername = null; }
            if (psPassword == "") { psPassword = null; }
            //if force, unmap ready for new connection
            //if (lf_Force) { try { zUnMapDrive(true); } catch { } }
            //call and return
            int i = WNetAddConnection2A(ref stNetRes, psPassword, psUsername, iFlags);
            if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
        }
        // Unmap network drive
        private void zUnMapDrive(bool pfForce)
        {
            //call unmap and return
            int iFlags = 0;
            //if (lf_Persistent) { iFlags += CONNECT_UPDATE_PROFILE; }
            int i = WNetCancelConnection2A(ls_Drive, iFlags, Convert.ToInt32(pfForce));
            if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
        }
        // Check / Restore a network drive
        private void zRestoreDrive()
        {
            //call restore and return
            int i = WNetRestoreConnectionW(0, null);
            if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
        }
        // Display windows dialog
        private void zDisplayDialog(Form poParentForm, int piDialog)
        {
            int i = -1;
            int iHandle = 0;
            //get parent handle
            if (poParentForm != null)
            {
                iHandle = poParentForm.Handle.ToInt32();
            }
            //show dialog
            if (piDialog == 1)
            {
                i = WNetConnectionDialog(iHandle, RESOURCETYPE_DISK);
            }
            else if (piDialog == 2)
            {
                i = WNetDisconnectDialog(iHandle, RESOURCETYPE_DISK);
            }
            if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
            //set focus on parent form
            poParentForm.BringToFront();
        }
    }
}



With the above code, I am able to map a folder which is stored in C:\

But I want to map a folder which is stored may be in C:\Program Files\XXXXX\SharedFolder

Please help me with this.

--
AJ
Posted

1 solution

I don't see a problem here. You already can map network shares. What's the remaining problem? How to handle the shared file from the client side?

(Sorry if I'm answering a wrong question here, please feel free to correct me.)
This is very simple, all about naming conventions. See, for example http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx[^], pay attention for Title "Naming conventions" and the example of "\\server\share\path\file".

—SA
 
Share this answer
 
Comments
ankitjoshi24 20-Apr-11 14:05pm    
I am not facing the problem with the above code if the file is shared in C:\

But if I have a file shared in C:\Program Files\XXXX\SharedFile then there would not be any mapping done as Program Files and XXXX are not shared.

So my concern was if I could get to SharedFile without sharing Program Files and XXXX folders

Thank you for helping

--
AJ
Sergey Alexandrovich Kryukov 20-Apr-11 14:22pm    
You should not really share anything in that Program Files folder. Do you share executables?

You can also considering sharing data and/or services, not files. Sharing files is actually a very archaic and unsafe technique. You could use low-level networking, remoting or WCF instead.

--SA
ankitjoshi24 20-Apr-11 15:43pm    
I am using WCF in that case. So you mean it is not safe to share anything from program files? What if the computer is in a secured network. Still are there problem in sharing the program files folder?
Sergey Alexandrovich Kryukov 20-Apr-11 16:10pm    
Well, if an extra share would give you some benefits like performance you could rely on the security of your inner network/intranet. But it does not give you any. Except some simplicity, but even the simplicity works for you only only on your first steps, not as long-term investment.

As as a long-term issue, network share is only a support problem: what if file structure changes? You need to change data on both sides. It is a problem due to violation of Don't Repeat Yourself (D.R.Y.) Principle (see in Wikipeda). With remoting/WCF you can have your own ***signle*** configuration file or database to store all your run-time parameter is one place; and also you can use Data Contract and/or Service Contract compiled from a single source.
(There can be different approach to centralized data, but the key is that you're free to develop anything to suit your needs.)

In this way in longer-term considerations remoting/WCF is much better.

Or! I did not even mentioned inter-platform compatibility. You can have .NET (in the form of Mono software) run and Linux, Mac and many more OS's and reuse your Windows-borne codes without recompilation (I do that on my Linux machine). This is a huge benefit if you ever consider interoperability between different platforms.

--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900