我正在使用以下代碼將寫入txt文件的十六進制字符串轉換爲 字節文件。問題是它不處理大的txt文件,我得到「內存不足異常」 。我知道它應該在「塊」中完成,但我不能 正確。十六進制爲字節塊
請幫忙!代碼:
protected void Button1_Click(object sender, EventArgs e)
{
{
string tempFileName = (Server.MapPath("~\\Tempfolder\\" + FileUpload2.FileName));
using (FileStream fs = new FileStream(tempFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader sr = new StreamReader(fs))
{
string s = (sr.ReadToEnd());
if (s.Length % 2 == 1) { lblispis.Text = "String must have an even length"; }
else
{
string hexString = s;
File.WriteAllBytes(tempFileName + ".bin", StringToByteArray(hexString));
lblispis.Text = "Done.";
}
}
}
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars/2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i/2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
+1,這基本上它。 – Groo