C#IO流的操作
C# IO流的操作非常重要,我们读写文件都会使用到这个技术,这里先演示一个文件内容复制的例子,简要说明C#中的IO操作。

10多年建站经验, 成都做网站、成都网站建设客户的见证与正确选择。创新互联提供完善的营销型网页建站明细报价表。后期开发更加便捷高效,我们致力于追求更美、更快、更规范。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//将文件内容读到流中
Stream stream = File.Open("test.txt", FileMode.OpenOrCreate);
//初始化一个字节数组
byte[] bytes = new byte[(int)stream.Length];
//将流读到字节数组中
stream.Read(bytes, 0, bytes.Length);
//用MemoryStream接收
MemoryStream ms = new MemoryStream(bytes);
//从开始处设置
ms.Seek(0, SeekOrigin.Begin);
//再把返回的MemoryStream 写到另一个文件中去
ms.WriteTo(new FileStream("newFile.txt", FileMode.OpenOrCreate));
}
}
}Stream是一个抽象类,而MemoryStream和FileStream都是Sream的子类。
而下面这个例子则演示了异步读取txt文本内容的方法。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetTxt().Result);
}
///
/// 异步读取txt文本内容
///
///
public static async Task GetTxt()
{
using (Stream stream = File.Open("test.txt", FileMode.OpenOrCreate))
{
using (StreamReader sr = new StreamReader(stream, Encoding.Default))
{
return await sr.ReadToEndAsync();
}
}
}
}
} 关于IO更多的类以及操作请参考:https://msdn.microsoft.com/zh-cn/library/system.io(v=vs.110).aspx。
网页标题:C#IO流的操作
本文链接:http://www.jxjierui.cn/article/ihoosc.html


咨询
建站咨询
