1. 程式人生 > >文件與字符串之間的轉換

文件與字符串之間的轉換

實例化 循環 param turn lose open mba read 數據讀取

/// <summary>
/// 將傳進來的文件轉換成字符串
/// </summary>
/// <param name="FilePath">待處理的文件路徑(本地或服務器)</param>
/// <returns></returns>
public string FileToBinary(string FilePath)
{
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);

//利用新傳來的路徑實例化一個FileStream對像
int fileLength = Convert.ToInt32(fs.Length);
//得到對像大小
byte[] fileByteArray = new byte[fileLength];
//聲明一個byte數組
BinaryReader br = new BinaryReader(fs);
//聲明一個讀取二進流的BinaryReader對像
for (int i = 0; i < fileLength; i++)
{//循環數組
br.Read(fileByteArray, 0, fileLength);
//將數據讀取出來放在數組中
}
string strData = Convert.ToBase64String(fileByteArray);
//裝數組轉換為String字符串
return strData;
}

/// <summary>
/// 將傳進來的字符串保存為文件
/// </summary>

/// <param name="path">需要保存的位置路徑</param>
/// <param name="binary">需要轉換的字符串</param>
public void BinaryToFile(string path, string binary)
{
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
//利用新傳來的路徑實例化一個FileStream對像
BinaryWriter bw = new BinaryWriter(fs);
//實例化一個用於寫的BinaryWriter
bw.Write(Convert.FromBase64String(binary));
bw.Close();
fs.Close();
}

文件與字符串之間的轉換