zoukankan      html  css  js  c++  java
  • C# 中的 IO

    C#与Java不同,不区分字符流、字节流,采用Stream方式,针对Stream提供Reader与Writer的相关操作。
    摘几篇msdn的demo:
    1.写操作 StreamWriter 类
    StreamWriter 实现TextWriter接口,旨在以一种特定的编码输出字符,而从 Stream 派生的类则用于字节的输入和输出。

    
    using System;
    using System.IO;
    
    class Test 
    {
        public static void Main() 
        {
            // Create an instance of StreamWriter to write text to a file.
            // The using statement also closes the StreamWriter.
            using (StreamWriter sw = new StreamWriter("TestFile.txt")) 
            {
                // Add some text to the file.
                sw.Write("This is the ");
                sw.WriteLine("header for the file.");
                sw.WriteLine("-------------------");
                // Arbitrary objects can also be written to the file.
                sw.Write("The date is: ");
                sw.WriteLine(DateTime.Now);
            }
        }
    }
    
    2. 读操作 StringReader类
    实现从字符串进行读取的 TextReader。
    
    using System;
    using System.IO;
    
    class Test 
    {
        public static void Main() 
        {
            try 
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader("TestFile.txt")) 
                {
                    String line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null) 
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception e) 
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
    }
    

    关于C# IO操作详见msdn后续还会完善下最近工作中碰到的IO类

  • 相关阅读:
    .NET基础示例系列之十二:DLLImport
    .NET基础示例系列之二:Socket
    Qt之msvcversion.conf loaded but QMAKE_MSC_VER isn‘t set
    Ubuntu安装sshd
    Quick工程设置exe图标
    git修改文件之后上传
    VS里打开Qt的pro工程
    QtQWebEngineView显示百度网页
    在gitte建立新仓库并上传本地工程
    Qt的qDebug打印加颜色
  • 原文地址:https://www.cnblogs.com/shuoli/p/7478511.html
Copyright © 2011-2022 走看看