Authenticate to Network Drive


Windows Application
MS. Visual Studio 2008 Profesional Edition


มีสมาชิกgreatfriends M ถามถึง วิธีการ Authentication ถายในโปรแกรมเพื่อเข้าใช้งานไฟล์ที่แชร์ไว้ในเครื่องอื่น และคำถามบนgreatfriends จึงจัดให้ครับ…


การแชร์ไฟล์ข้อมูลไว้บน Server เมื่อเราต้องการควบคุมความถูกต้องของข้อมูลโดยไม่ให้ User เข้าถึงข้อมูลใน Folder ได้โดยตรง แต่ให้ User ใช้งานผ่าน interface (UI) เพื่อเข้าถึง Folder ข้อมูลนั้นๆ โดยการ Authenticate local user บน Server ผ่าน interface ของเรา

การ Authenticate local user บน Server ทำได้โดยใช้งานfunction LogonUser() ใน advapi32.dll มาใช้งาน ซึ่ง advapi32.dll มันเป็น part หนึ่งของ advanced API services library มีมาตั้งแต่ Windows NT 4.0 ข้อมูลเกียวกับadvapi32.dll หาได้จาก ข้อมูลอ้างอิง หรือ Search จาก Google:=>advapi32.dll ???

การทำงานของระบบ

1. User interface (UI)

PUT = Uploads, GET = Downloads

clip_image001

2. Put (Upload file)

clip_image002

3. เลือก destination path (Remote path) จะเห็นว่าเป็นการ Brow Folder บน Server

clip_image005

4.Remote path on 192.169.0.202C$Test (Folder C:Test บน server ไม่จำเป็นต้องแชร์ ครับ เพียงแค่เราฝัง User ที่สามารถ Read Write Folder นั้นๆ ไว้ในโปรแกรมของเรา )

clip_image006

7. COPY Click

clip_image007

8.PUT (upload) successded

clip_image008

9. ตรวจสอบ file บน server IP: 192.169.0.202 เห็นว่ามีไฟล์บน Server เรียบร้อย

clip_image009

10.GET files (Download). select folder path บน Local Drive

clip_image010

11. select remote file path จะเห็นว่า Brow file บน Server

clip_image011

12. select remote file บน Server

clip_image012

13. COPY Click

clip_image013

14. GET(download) File Success

clip_image014

15 ตรวจสอบ on local drive

clip_image015

16. ออกแบบ UserInterface ตามรูปครับ

16

 

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;

using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

namespace Authenticate2NetworkDrive
{
    public partial class Form1 : Form
    {
        FolderBrowserDialog folderBrowserDialog1;
        OpenFileDialog openFileDialog1;

       [DllImport("advapi32.DLL", SetLastError = true)]
        static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
        public Form1()
        {
            InitializeComponent();
        }

        private void btCOPY_Click(object sender, EventArgs e)
        {
            IntPtr admin_token = IntPtr.Zero;
            WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
            WindowsIdentity wid_admin = null;
            WindowsImpersonationContext wic = null;
            try
            {
               if ((LogonUser(this.txtUserName.Text.Trim (),
                    this.txtDomain.Text.Trim(),
                    this.txtPassword.Text.Trim(),
                    9,//LogonType.LOGON32_LOGON_NEW_CREDENTIALS,
                    0,
                    ref  admin_token) != 0))
                {
                    wid_admin = new WindowsIdentity(admin_token);
                    wic = wid_admin.Impersonate();

                    if (radPUT.Checked )
                        System.IO.File.Copy(txtLocal.Text, txtRemote.Text, true);//PUT
                    else
                        System.IO.File.Copy(txtRemote.Text, txtLocal.Text, true);//GET

                    MessageBox.Show("Copy succeeded");
                }
                else
                {
                    MessageBox.Show("Copy Failed");
                }
            }
            catch (System.Exception se)
            {
                int ret = Marshal.GetLastWin32Error();
                MessageBox.Show(ret.ToString(), ("Error code: "
                                + (ret.ToString() + ("rn" + se.Message))));
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btBrowLocal_Click(object sender, EventArgs e)
        {
            if (radPUT.Checked)
            {
                openFileDialog1 = new OpenFileDialog();

                openFileDialog1.InitialDirectory = "c:\";
                openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                openFileDialog1.FilterIndex = 2;
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (openFileDialog1.OpenFile() != null)
                        {
                            txtLocal.Text = openFileDialog1.FileName;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    }
                }
            }
            else {
                folderBrowserDialog1 = new FolderBrowserDialog();
                DialogResult result = folderBrowserDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    txtLocal.Text = folderBrowserDialog1.SelectedPath;
                }

            }

        }

        private void btBrowRemot_Click(object sender, EventArgs e)
        {
            openFileDialog1 = new OpenFileDialog();

            if (radPUT.Checked)
            {
                 IntPtr admin_token = IntPtr.Zero;
                WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
                WindowsIdentity wid_admin = null;
                WindowsImpersonationContext wic = null;

                try
                {
                    if ((LogonUser(this.txtUserName.Text.Trim(),
                    this.txtDomain.Text.Trim(),
                    this.txtPassword.Text.Trim(),
                        9,//LogonType.LOGON32_LOGON_NEW_CREDENTIALS,
                        0,
                        ref  admin_token) != 0))
                    {
                        wid_admin = new WindowsIdentity(admin_token);
                        wic = wid_admin.Impersonate();

                        folderBrowserDialog1 = new FolderBrowserDialog();
                        folderBrowserDialog1.Description = "Select Folder";

                       // Brow Folder path บน Remote Server
                        folderBrowserDialog1.SelectedPath = "\\" + txtIPServer.Text + "\" + txtNetworkDrive.Text  + "\";

                        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                        {
                            System.IO.FileInfo fi = new System.IO.FileInfo(txtLocal.Text );
                            txtRemote.Text = folderBrowserDialog1.SelectedPath + "\" + fi.Name ;
                        }
                    }
                }
                catch (System.Exception se)
                {
                    int ret = Marshal.GetLastWin32Error();
                    MessageBox.Show(ret.ToString(), ("Error code: "
                                    + (ret.ToString() + ("rn" + se.Message))));
                }
                finally
                {
                    if (wic != null)
                    {
                        wic.Undo();
                    }
                }

            }
            else
            {
                IntPtr admin_token = IntPtr.Zero;
                WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
                WindowsIdentity wid_admin = null;
                WindowsImpersonationContext wic = null;

                try
                {
                    if ((LogonUser(this.txtUserName.Text.Trim(),
                    this.txtDomain.Text.Trim(),
                    this.txtPassword.Text.Trim(),
                        9,//LogonType.LOGON32_LOGON_NEW_CREDENTIALS,
                        0,
                        ref  admin_token) != 0))
                    {
                        wid_admin = new WindowsIdentity(admin_token);
                        wic = wid_admin.Impersonate();

                      // Brow file path บน Remote Server
                        openFileDialog1.InitialDirectory ="\\"+ txtIPServer.Text + "\c$\";
                        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                        openFileDialog1.FilterIndex = 2;
                        openFileDialog1.RestoreDirectory = true;

                        if (openFileDialog1.ShowDialog() == DialogResult.OK)
                        {
                            try
                            {
                                if (openFileDialog1.OpenFile() != null)
                                {
                                    txtRemote.Text = openFileDialog1.FileName;

                                    System.IO.FileInfo fi = new System.IO.FileInfo(txtRemote.Text);
                                    txtLocal.Text = txtLocal.Text + "\" + fi.Name;
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                            }
                        }
                    }

                    else
                    {
                        MessageBox.Show("Copy Failed");
                    }
                }
                catch (System.Exception se)
                {
                    int ret = Marshal.GetLastWin32Error();
                    MessageBox.Show(ret.ToString(), ("Error code: "
                                    + (ret.ToString() + ("rn" + se.Message))));
                }
                finally
                {
                    if (wic != null)
                    {
                        wic.Undo();
                    }
                }
            }
        }

    }
}

ข้อมูลอ้างอิง:



LogonUser Function
LogonUser (advapi32)

Downloads:



Authenticate2NetworkDrive.zip
ชนิด: โฟลเดอร์ที่มีการบีบอัด (Zip)
ขนาด: 46.3 กิโลไบต์
ปรับเปลี่ยนล่าสุด: 12/2/2551 22:41:10
Authenticate2NetworkDrive.zip

 

Advertisements
เกี่ยวกับ

Nuchit Atjanawat is a Microsoft MVP, GreatFriends Community Leader, WindowsITPro Columnist(Mr.Nano), Silverlight Business Application Instructor, Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession. He has a very good skill over Silverlight, LightSwitch, C#, XAML & Blend. He shares his technical findings, tutorials in his technical blog. Follow his Blog and Facebook page to be updated on latest articles. - Technical Blog: https://janawat.wordpress.com - WindowsITPro Columnist(Mr.Nano): http://windowsitpro.net - The GreatFriends.Biz Community Discussion Board (nano): http://greatfriends.biz - witter: https://twitter.com/janawat - Facebook Page: https://www.facebook.com/nuchit - Instructor: http://bit.ly/GF250-01, http://bit.ly/GF150-02

เขียนใน Windows Application

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out / เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out / เปลี่ยนแปลง )

Google+ photo

You are commenting using your Google+ account. Log Out / เปลี่ยนแปลง )

Connecting to %s

In Archive
%d bloggers like this: