上篇已經提到如何利用序列化產生Xml文件( [XML][C#.NET] 處理 ezTRACK 的 EPCIS Xml文件 ),這篇是說明如何將Xml文件上傳到ezTRACK
先建立起方法模組:
public bool Upload( string FileName) { if ( string .IsNullOrEmpty(FileName)) throw new ArgumentNullException( "FileName" ); if (!File.Exists(FileName)) throw new FileNotFoundException( "FileName" ); string fileName = FileName; string serverUrl = "ezTRACK網址" ; string account = "帳號" ; string password = "密碼" ; Stream requestStream = null ; FileStream fileStream = null ; HttpWebRequest uploadRequest = null ; HttpWebResponse uploadResponse = null ; //忽略驗証 ServicePointManager.ServerCertificateValidationCallback = delegate { return true ; }; try { //DOTO:1.Create WebRequest //DOTO:2.Creat Request Stream //DOTO:3. Write Request Stream } catch { throw ; } finally { if (uploadResponse != null ) uploadResponse.Close(); if (fileStream != null ) fileStream.Close(); if (requestStream != null ) requestStream.Close(); } }
DOTO:1.所要做的是建立WebRequest
uploadRequest = WebRequest.Create(serverUrl) as HttpWebRequest; uploadRequest.Method = "POST" ; //uploadRequest.Method = WebRequestMethods.Http.Post; uploadRequest.ContentType = "application/soap+xml; charset=utf-8" ; uploadRequest.Credentials = new NetworkCredential(account, password);
DOTO:2.所要做的是建立RequestStream,把硬碟裡的檔案讀進來
requestStream = uploadRequest.GetRequestStream(); fileStream = File.Open(fileName, FileMode.Open); byte [] buffer = new byte [1024]; int bytesRead; while ( true ) { bytesRead = fileStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) break ; requestStream.Write(buffer, 0, bytesRead); }
DOTO:3. 當 Request Stream 關閉後就寫入到 Server,利用HttpStatusCode判斷是否上傳成功
requestStream.Close(); uploadResponse = uploadRequest.GetResponse() as HttpWebResponse; if (uploadResponse.StatusCode == HttpStatusCode.OK) return true ; else return false ;