天天看點

讀取檔案轉換為byte陣列

讓wdinwos Server去監控某一檔案夾,是否有新檔案産生,如果有的話,即把它上傳至網際網路上一台雲伺服器上。

剛開始,我是寫了一個Windows Service的,但InstallUtil.exe之後,它死活沒有把檔案夾新建立的檔案上傳。

後來,不得不寫成一個控制台應用程式。後來查找到相關資料,如果與桌面有互動的,還是寫成控制台應用程式較好。

由于上傳的檔案存放的伺服器是,網際網路雲伺服器。Insus.NET想過許多方案,最終是将檔案轉換為資料流,上傳至雲伺服器ms sql server。

基中,有一個方法,根據路徑檔案轉換為資料流的方法:

​​

讀取檔案轉換為byte陣列
讀取檔案轉換為byte陣列
讀取檔案轉換為byte陣列

using System;     using System.Collections.Generic;     using System.IO;     using System.Linq;     using System.Web;     namespace Insus.NET.Utility     {         public static class ImgUtil         {             public static byte[] ReadFileToByteArray(string filePath)             {                 byte[] buffer;                 FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);                 try                 {                     int length = (int)fileStream.Length;                     buffer = new byte[length];                     int count;                     int sum = 0;                     while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)                         sum += count;                 }                 finally                 {                     fileStream.Close();                 }                 return buffer;             }         }     }      

Source Code