我們將設計一個下載網頁, 點download鍵, 將會透過web server, 經由網路芳鄰去file server的c:\remote_files, 將AA.txt下載, 操作如下圖。
設定web server
1. web server 建一帳號IUSER_REMOTE, 設定密碼1234- 只打勾”密碼永遠有效”
2. 進入IIS-應用程式虛擬目錄-目錄安全設定
- uncheck 允許IIS來控制密碼,
- 使用者/密碼, 改為IUSER_REMOTE/1234
設定File server
1. 建一帳號IUSER_REMOTE, 設定密碼1234- 只打勾”密碼永遠有效”
- 設定共用
- 使用權限給IUSER_REMOTE讀寫的權限
回到Web Server設定Web.config
1. 到你的web目錄下, 打開web.coonfig, system.web裡加入identity標籤並設定impersonate為true <system.web>
<identity impersonate="true"/>
</system.web>
但以上適用在"IIS驗證帳號"而已2. 我們設定了新帳號, 要用以下的指令
<system.web>3. 修改WEB 主機目錄權限
<identity impersonate="true" userName="IUSER_REMOTE" password="1234" />
</system.web>
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
賦與IUSER_REMOTE讀寫權限
開始進行程式
在寫程式之前要先了解UNC(Universal Naming Convention) 的路逕, 是像這樣\\Fileserver\FolderName\Files\File1.txt, 也就是網路芳鄰上的打法 ,另外在coding 前先了解asp.net 幾種檔案下載方式比較 , 這裡我們使用HttpResponse.WriteFile , 因為它支援UNC路徑, 以下是範例程式: protected void Button1_Click(object sender, EventArgs e)
{
string fileNmae ;
fileNmae = @"\\192.168.1.1\remote_files\aa.txt";
if (System.IO.File.Exists(fileNmae.Trim()))
{
Response.Write(fileNmae);
Send(Context, fileNmae);
}
}
public static void Send(HttpContext context, string fileName)
{
HttpResponse response = context.Response;
HttpCookie cookie = context.Request.Cookies["downloadstatus"];
if (cookie == null)
{
cookie = new HttpCookie("downloadstatus", String.Empty);
}
HttpCookie errorCookie = new HttpCookie("downloaderror", string.Empty);
FileInfo TheFile = new FileInfo(fileName);
if (TheFile.Exists)
{
//將檔案下載--
response.Clear();
cookie.Value = "success";
response.SetCookie(cookie); //寫入cookie
response.Buffer = true;
response.AddHeader("content-disposition", "attachment;filename=" + TheFile.Name);//檔頭
response.Charset = "";
response.ContentType = GetContentType(TheFile.Name);//取得Content Type
response.WriteFile(TheFile.FullName, false);//輸出檔案
response.Flush();
response.End();
//--------------
}
else
{
//將cookie設為錯誤
cookie.Value = "fail";
errorCookie.Value = "File " + TheFile.Name + " doesn't exists on the server";
response.SetCookie(cookie);
response.SetCookie(errorCookie);
}
}
//取得Content Type
public static string GetContentType(string fileName)
{
string contentType = "application/octetstream";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (registryKey != null && registryKey.GetValue("Content Type") != null)
contentType = registryKey.GetValue("Content Type").ToString();
return contentType;
}
後記
一般企業防火牆可能會關畢網路芳鄰的port 445, 在建置時要請網管打開。以上的範例是沒在AD下, 如果在AD下, 則帳號設定在AD上。
參考資訊:
http://support.microsoft.com/kb/306158
http://blog.miniasp.com/post/2007/11/10/How-to-write-file-to-net-share-folder-using-ASPNET.aspx
沒有留言:
張貼留言