藉助UploadHandler.ashx上傳文件到Web服務器的指定文件夾下服務器
UploadHandler.ashx代碼以下:spa
<%@ WebHandler Language="C#" CodeBehind="UploadHandler.ashx.cs" Class="WebApp.UploadHandler" %>
上傳文件代碼以下:code
using System; using System.IO; using System.Net; namespace TestNew { class Program { static void Main(string[] args) { var Appclient = new WebClient(); var upTargetUri = new Uri("http://IP地址/WebApp/UploadHandler.ashx?fileName=./ClientBin/Files/test.txt"); try { FileInfo MyFile = new FileInfo(@"d:\test.txt"); FileStream MyStream = MyFile.Open(FileMode.Open, FileAccess.Read, FileShare.None); Appclient.OpenWriteAsync(upTargetUri, "POST", MyStream); Appclient.OpenWriteCompleted += delegate(object sender, OpenWriteCompletedEventArgs e) { //將圖片數據流發送到服務器上 Stream inputStream = e.UserState as Stream; Stream outputStream = e.Result; byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) { outputStream.Write(buffer, 0, bytesRead); } outputStream.Close(); inputStream.Close(); }; } catch (Exception e) { Console.WriteLine("文件上傳失敗,請稍候重試:" + e.Message); } Console.ReadKey(); } } }