C#有提供file.copy的方式對檔案做覆製貼上的功能
但有時想透過web-service或是WCF去傳輸檔案
此時就須要將檔案轉換成二位元的格式, 而WCF所接收的值只能是可序列化的值所以在做檔案傳輸的時候就需轉換檔案的格式
當然WCF有傳輸大小的限制(如何修改請看另一篇)
第一步當然是先有檔案基本資訊 (64base encode)
FileStream inFile = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
再做檔案的轉換 轉換成長格式(64位元的string)
byte[] binaryData = new Byte[inFile.Length];
long bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length);
inFile.Close();
base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);
或是以下方式
using (FileStream reader = new FileStream(fileName, FileMode.Open))
{
byte[] buffer = new byte[reader.Length];
reader.Read(buffer, 0, (int)reader.Length);
return Convert.ToBase64String(buffer);
}
以上兩個方法皆為轉換檔案成64bit的string格式.
當然接收的的部分也有兩個方法 (64base decode)
先指定一個接收的檔案路徑和而以下的filePath的部分需要自已給定檔案的儲存路徑。(例:D:\testing.txt)
FileStream inFile = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] buffer = Convert.FromBase64String(serializedFile);
reader.Write(buffer, 0, buffer.Length);
inFile.Close();
或者
public static void DeSerialize(string fileName, string serializedFile)
{
using (System.IO.FileStream reader = System.IO.File.Create(fileName))
{
byte[] buffer = Convert.FromBase64String(serializedFile);
reader.Write(buffer, 0, buffer.Length);
}
}
此兩種皆為序列化方法
留言列表