文件流操作(FileStream,StreamReader,StreamWriter)

大文件拷贝:

 /// <summary>
/// 大文件拷贝
/// </summary>
/// <param name="sSource"></param>
/// <param name="sTarget"></param>
private static void CopyFile(string sSource, string sTarget)
{
using (FileStream fsRead=new FileStream(sSource,FileMode.Open,FileAccess.Read))
{
using (FileStream fsWrite=new FileStream(sTarget,FileMode.Create,FileAccess.Write))
{
double n = (double)fsRead.Length;
Stopwatch sw = new Stopwatch(); sw.Start();
while (true)
{
//定义一个6MB的缓冲区
byte[] buffer = new byte[ * * ];
int m = fsRead.Read(buffer, , buffer.Length); if (m==)
{
break;
}
else
{
fsWrite.Write(buffer, , m);
double dl = Math.Round(((double)fsWrite.Position / n) * , );
Console.WriteLine("总进度:{0}%", dl);
}
}
sw.Stop();
double iTime = Math.Round((double)sw.ElapsedMilliseconds / , );
Console.WriteLine("总运行时间:"+iTime+"秒");
}
}
}

FileStream是对字节(byte)的操作,上面这种方法拷贝电影文件,大的压缩文件等没问题,但是对于文本文件多半使用后面2个类StreamReader,StreamWriter,

 #region 使用StreamWriter进行写
using (StreamWriter sw = new StreamWriter(@"D:\demo.txt"))
{
for (int i = ; i <= ; i++)
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd") + "\t" + i.ToString());
}
}
Console.WriteLine("OK");
#endregion
 #region 使用StreamReader进行读
using (StreamReader sr = new StreamReader(@"D:\demo.txt"))
{
string s = sr.ReadLine();
while (!string.IsNullOrEmpty(s))
{
Console.WriteLine(s);
s = sr.ReadLine();
}
}
#endregion
上一篇:EntityFrame CodeFirst 自动生成表


下一篇:(转)SSL/TLS 漏洞“受戒礼”,RC4算法关闭