ASP.NET中使用網路磁碟機

來源:互聯網
上載者:User

搞了一個圖片網站,圖片放在機器A,後台管理網站放在機器B。既然是管理,少不了要對圖片進行刪除什麼的。那象我們這種情況,該如何處理?

1、可以在機器A搞個WebService

2、也可以在機器A搞個遠程調用

3、在機器A上將圖片存放目錄共用,然後機器B映射為網路磁碟機

決定採用方法3。

步驟如下:

0、假設機器A(圖片伺服器), 電腦名稱為jsj-01,IP為192.168.0.1;

      機器B(後台管理網站)

1、機器A和機器B都分別建立一個名字、密碼相同的帳號,比如coder/123456。

2、機器A上將圖片目錄共用(img),將coder賦予讀寫權限。注意 共用和安全 兩個地方都要賦。

3、建立兩個類,代碼如下(照抄可也,我也是抄的)

using System;using System.Collections.Generic;using System.Linq;using System.Web;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;    }}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;            }        }    }}

4、然後在後台管理網站中使用這個網路磁碟機Z。使用的方法就是引用新寫的這個類

    protected void btnDelete_Click(object sender, EventArgs e)    {        //刪除圖片        using (LogonImpersonate imper = new LogonImpersonate("code", "123456"))        {            uint state = 0;            if (!Directory.Exists("w:"))            {                state = WNetHelper.WNetAddConnection(@"jsj-01\coder", "123456", @"\\192.168.0.1\Img", "z:");            }            if (!state.Equals(0))            {                throw new Exception("添加網路磁碟機錯誤,錯誤號碼:" + state.ToString());            }             File.Delete(圖片路徑);        }    }

將共用目錄映射為Z。

首先是將IIS的賬戶替換,然後訪問網路磁碟機。注意用上了using,目的是只在訪問該網路磁碟機的時候使用,用完即棄,恢複預設身份,否則其他的操作就不行了。

參考文章

http://www.cnblogs.com/sqzhuyi/archive/2011/01/15/aspnet-remote.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.