ASP.NET訪問網路磁碟機(映射磁碟)

來源:互聯網
上載者:User

也許很多朋友在做WEB項目的時候都會碰到這樣一個需求:

當使用者上傳檔案時,需要將上傳的檔案儲存到另外一台專門的檔案伺服器。

 

要實現這樣一個功能,有兩種解決方案:

方案一、在檔案伺服器上建立一網站,用來接收上傳的檔案,然後儲存。

方案二、將檔案伺服器的指定目錄共用給WEB伺服器,用來儲存檔案。

 

方案一不用多說,應該是很簡單的了,將上傳檔案的FORM表單的ACTION屬性指向檔案伺服器上的網站即可,我們來重點說下方案二。

 

也許你會說,其實方案二也很簡單,在WEB伺服器上做下磁碟映射,然後直接存取不就行了。其實不是這樣的,IIS預設賬戶為NETWORK_SERVICE,該賬戶是沒許可權訪問共用目錄的,所以當你把網站部署到IIS上的時候,再訪問映射磁碟就會報“找不到路徑”的錯誤。所以,直接建立磁碟映射是行不通的,我們需要在程式中用指定賬戶建立映射,並用該賬戶運行IIS進程,下面來說下詳細步驟及相關代碼。

 

1、在檔案伺服器上建立共用目錄,並建立訪問賬戶。

比如共用目錄為://192.168.0.9/share

訪問賬戶為:user-1 密碼為:123456

 

2、在WEB伺服器上建立使用者:user-1 密碼為:123456,使用者組選擇預設的user組即可。

 

3、在WEB項目中建立公用類WNetHelper

using System.Runtime.InteropServices;public class WNetHelper{    [DllImport("mpr.dll", EntryPoint = "WNetAddConnection2")]    private static extern uint WNetAddConnection2(NetResource lpNetResource, string lpPassword, string lpUsername, uint dwFlags);    [DllImport("Mpr.dll", EntryPoint = "WNetCancelConnection2")]    private static extern uint WNetCancelConnection2(string lpName, uint dwFlags, bool fForce);    [StructLayout(LayoutKind.Sequential)]    public class NetResource    {        public int dwScope;        public int dwType;        public int dwDisplayType;        public int dwUsage;        public string lpLocalName;        public string lpRemoteName;        public string lpComment;        public string lpProvider;    }    /// <summary>    /// 為網際網路共用做本機對應   /// </summary>    /// <param name="username">訪問使用者名稱(windows系統需要加電腦名稱,如:comp-1/user-1)</param>    /// <param name="password">訪問使用者密碼</param>    /// <param name="remoteName">網際網路共用路徑(如://192.168.0.9/share)</param>    /// <param name="localName">本機對應盤符</param>    /// <returns></returns>    public static uint WNetAddConnection(string username, string password, string remoteName, string localName)    {        NetResource netResource = new NetResource();        netResource.dwScope = 2;        netResource.dwType = 1;        netResource.dwDisplayType = 3;        netResource.dwUsage = 1;        netResource.lpLocalName = localName;        netResource.lpRemoteName = remoteName.TrimEnd('//');        uint result = WNetAddConnection2(netResource, password, username, 0);        return result;    }    public static uint WNetCancelConnection(string name, uint flags, bool force)    {        uint nret = WNetCancelConnection2(name, flags, force);        return nret;    }}

 

4、為IIS指定運行賬戶user-1

要實現此功能,有兩種辦法:

a) 在web.config檔案中的<system.web>節點下,添加如下配置:<identity impersonate="true" userName="user-1" password="123456" />

b) 在WEB項目中添加公用類LogonImpersonate

public class LogonImpersonate : IDisposable{    static public string DefaultDomain    {        get        {            return ".";        }    }    const int LOGON32_LOGON_INTERACTIVE = 2;    const int LOGON32_PROVIDER_DEFAULT = 0;    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]    extern static int FormatMessage(int flag, ref   IntPtr source, int msgid, int langid, ref   string buf, int size, ref   IntPtr args);    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]    extern static bool CloseHandle(IntPtr handle);    [System.Runtime.InteropServices.DllImport("Advapi32.dll", SetLastError = true)]    extern static bool LogonUser(    string lpszUsername,    string lpszDomain,    string lpszPassword,    int dwLogonType,    int dwLogonProvider,    ref   IntPtr phToken    );    IntPtr token;    System.Security.Principal.WindowsImpersonationContext context;    public LogonImpersonate(string username, string password)    {        if (username.IndexOf("//") == -1)        {            Init(username, password, DefaultDomain);        }        else        {            string[] pair = username.Split(new char[] { '//' }, 2);            Init(pair[1], password, pair[0]);        }    }    public LogonImpersonate(string username, string password, string domain)    {        Init(username, password, domain);    }    void Init(string username, string password, string domain)    {        if (LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref   token))        {            bool error = true;            try            {                context = System.Security.Principal.WindowsIdentity.Impersonate(token);                error = false;            }            finally            {                if (error)                    CloseHandle(token);            }        }        else        {            int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();            IntPtr tempptr = IntPtr.Zero;            string msg = null;            FormatMessage(0x1300, ref   tempptr, err, 0, ref   msg, 255, ref   tempptr);            throw (new Exception(msg));        }    }    ~LogonImpersonate()    {        Dispose();    }    public void Dispose()    {        if (context != null)        {            try            {                context.Undo();            }            finally            {                CloseHandle(token);                context = null;            }        }    }}

在訪問映射磁碟之前首先調用此類為IIS更換運行使用者:LogonImpersonate imper = new LogonImpersonate("user-1", "123456");

 

5、在訪問共用目錄前,調用WNetHelper.WNetAddConnection,添加磁碟映射

public static bool CreateDirectory(string path){    uint state = 0;    if (!Directory.Exists("Z:"))    {        state = WNetHelper.WNetAddConnection(@"comp-1/user-1", "123456", @"//192.168.0.9/share", "Z:");    }    if (state.Equals(0))    {        Directory.CreateDirectory(path);        return true;    }    else    {        throw new Exception("添加網路磁碟機錯誤,錯誤號碼:" + state.ToString());    }}

 

6、完成。

 

簡潔代碼就是:

LogonImpersonate imper = new LogonImpersonate("user-1", "123456");

WNetHelper.WNetAddConnection(@"comp-1/user-1", "123456", @"//192.168.0.9/share", "Z:");
Directory.CreateDirectory(@"Z:/newfolder");

file1.SaveAs(@"Z:/newfolder/test.jpg");

 

有不明白的可以發EMAIL給我:sqzhuyi@gmail.com

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.