个人倾向使用File.WriteAllByte写入文件:
//Stream to File MemoryStream ms=...Stream; ms.Position = 0; byte[] buffer = new byte[ms.Length]; ms.Read(buffer, 0, (int)ms.Length); File.WriteAllBytes(filepath, buffer);//写入文件
StreamRead,StreamWrite,SreamRead,以及File的部分操作
// StreamRead,StreamWrite,File只能操作文本文件
//FileStream可以操作所有格式 包括文本,文件,图片,视频 //SreamRead读取文件 using (StreamReader reader = new StreamReader(filepath)) { //reader.ReadLine();读取第一行 string data = reader.ReadToEnd();//读取所有 } //StreamWrite写入文件 using (StreamWriter writer = new StreamWriter(filepath)) { //writer.Write("写入的内容"); //也可以如下面一行一行写入 writer.WriteLine("0"); writer.WriteLine("1"); writer.WriteLine(picName); writer.WriteLine(txtCount.Text); } //File即可以读取文本 也可以写入文本 //读取 string data = File.ReadAllText(filepath); string[] datas = File.ReadAllLines(filepath); //写入 string[] ss = new string[] {"arr1","arr2" }; File.WriteAllLines(filepath, ss); File.WriteAllText(filepath, " 换行 ");
//附加
File.AppendAllLines(filepath,ss);
File.AppendAllText(filepath,str); //FileStream可以操作所有格式 包括文本,文件,图片,视频 //FileStream读取 string ss = null; byte[] buffer = new byte[1024 * 1024 * 1]; //针对大文件1M1M的读取 using (FileStream sr = new FileStream(sfilepath, FileMode.OpenOrCreate, FileAccess.Read)) { int sss = sr.Read(buffer, 0, buffer.Length); ss = Encoding.Default.GetString(buffer, 0, sss); } //FileStream写入 using (FileStream fsWrite = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer = Encoding.Default.GetBytes(str); fsWrite.Write(buffer, 0, buffer.Length); }
Stream 和 File 之间的转换
/// <summary> /// 将 Stream 写入文件 /// </summary> public void StreamToFile(Stream stream,string filepath) { // 把 Stream 转换成 byte[] byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); // 把 byte[] 写入文件 FileStream fs = new FileStream(filepath, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); } /// <summary> /// 从文件读取 Stream /// </summary> public Stream FileToStream(string filepath) { // 打开文件 FileStream fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read); // 读取文件的 byte[] byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); fileStream.Close(); // 把 byte[] 转换成 Stream Stream stream = new MemoryStream(bytes); return stream; }
文件复制(当然File.Copy更常用,这个是偶然中使用到整理的)
public static void CopyFile(string soucre, string target) { //读取的流 using (FileStream fsRead = new FileStream(soucre, FileMode.Open, FileAccess.Read)) { //写入的流 using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer = new byte[1024 * 1024 * 5]; while (true) { int r = fsRead.Read(buffer, 0, buffer.Length); //0代表已经读取完 if (r == 0) { break; } fsWrite.Write(buffer, 0, r); } } } }