//save binary bytes into file public bool saveBytesToFile(string fileToSave, ref Byte[] bytes, int dataLen, out string errStr) { bool saveOk = false; errStr = "未知错误!"; try { int bufStartPos = 0; int bytesToWrite = dataLen; FileStream fs; fs = File.Create(fileToSave, bytesToWrite); fs.Write(bytes, bufStartPos, bytesToWrite); fs.Close(); saveOk = true; } catch (Exception ex) { errStr = ex.Message; } return saveOk; }
例 10.2. saveBytesToFile 的使用范例
public bool downloadStMusicFile(string musicRealAddr, string fullnameToStore, out string errStr, Action<int> funcUpdateProgress) { bool downloadOk = false; errStr = "未知错误!"; if (musicRealAddr == null || musicRealAddr == "" || fullnameToStore == null || fullnameToStore == "") { errStr = "Songtaste歌曲真实的地址无效!"; return downloadOk; } Dictionary<string, string> headerDict = new Dictionary<string, string>(); //headerDict.Add("Referer", "http://songtaste.com/music/"); headerDict.Add("Referer", "http://songtaste.com/"); //const int maxMusicFileLen = 100 * 1024 * 1024; // 100M const int maxMusicFileLen = 300 * 1024 * 1024; // 300M Byte[] binDataBuf = new Byte[maxMusicFileLen]; int respDataLen = crl.getUrlRespStreamBytes(ref binDataBuf, musicRealAddr, headerDict, null, 0, funcUpdateProgress); if (respDataLen < 0) { errStr = "无法读取歌曲数据!"; return downloadOk; } if (crl.saveBytesToFile(fullnameToStore, ref binDataBuf, respDataLen, out errStr)) { downloadOk = true; }