zoukankan      html  css  js  c++  java
  • C# IO流的操作(一)

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

    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);
            }
    
            /// <summary>
            /// 异步读取txt文本内容
            /// </summary>
            /// <returns></returns>
            public static async Task<string> 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

  • 相关阅读:
    2015 HUAS Summer Contest#2~B
    2015 HUAS Summer Contest#2~A
    HUAS Summer Trainning #3~B
    HUAS Summer Trainning #3~A
    2015 HUAS Provincial Select Contest #1~D
    UVA 725
    货币体系
    N皇后摆放问题
    种子填充找连通块 floodfill
    二叉树的递归遍历,用先序和中序输出后序
  • 原文地址:https://www.cnblogs.com/guwei4037/p/4334997.html
Copyright © 2011-2022 走看看