zoukankan      html  css  js  c++  java
  • Simple Text File Operations in C#. example 武胜

    C-Sharp provides a File class which is used in manipulating text files. The File class is within the System namespace. Also we can use the StreamReader and StreamWriter classes, which are within the System.IO, namespace for reading from and writing to a text file. In this article we'll see examples of Creating a text file, reading contents of a text file and appending lines to a text file.

    1.Creating a Text File

    For creating text file we use the CreateText Method of the File Class. The CreateText methods takes in the path of the file to be created as an argument. It creates a file in the specified path and returns a StreamWriter object which can be used to write contents to the file.

    Example


    public class FileClass
    {
    public static void Main()
    {
    WriteToFile();
    }
    static void WriteToFile()
    {
    StreamWriter SW;
    SW=File.CreateText("c:\\MyTextFile.txt");
    SW.WriteLine("God is greatest of them all");
    SW.WriteLine("This is second line");
    SW.Close();
    Console.WriteLine("File Created SucacessFully");
    }
    }

    2.Reading Contents Of A Text File

    For reading the contents of a text file we use the OpenText Method of the File Class.The OpenText methods takes in the path of the file to be opened as an argument. It opens the specified file and returns a StreamReader object which can be used to read the contents of the file.

    Example


    public class FileClass
    {
    public static void Main()
    {
    ReadFromFile("c:\\MyTextFile.txt");
    }
    static void ReadFromFile(string filename)
    {
    StreamReader SR;
    string S;
    SR=File.OpenText(filename);
    S=SR.ReadLine();
    while(S!=null)
    {
    Console.WriteLine(S);
    S=SR.ReadLine();
    }
    SR.Close();
    }
    }

    3.Appending Content To A Text File

    For appending content to a text file we use the AppendText Method of the File Class. The AppendText methods takes in the path of the file to which the contents to be appended as an argument. It opens the file in the specified path and returns a StreamWriter object which can be used to append contents to the file.

    Example


    public class FileClass
    {
    public static void Main()
    {
    AppendToFile();
    }
    static void AppendToFile()
    {
    StreamWriter SW;
    SW=File.AppendText("C:\\MyTextFile.txt");
    SW.WriteLine("This Line Is Appended");
    SW.Close();
    Console.WriteLine("Text Appended Successfully");
    }
    }

  • 相关阅读:
    [1.2]由UML模型通过XMI生成XML,通过XSLT展示到表现层
    [1.1]XMI 与UML结合开发企业应用中业务模型
    如何创建脱机数据库应用程序思路
    SAML在无线网络传输的应用[对照文]
    SoberGGG对针式PKM的初次测评
    [转]美国知名天使投资人列出愿意投资的30大创意方向
    针式PKM适合哪些用户使用?
    没有个人知识管理就是觉得学了很多,却不得记到底学到了什么。
    [转]人之患在好为人师
    [转]一位中国的黑客的一封信!
  • 原文地址:https://www.cnblogs.com/zeroone/p/1716345.html
Copyright © 2011-2022 走看看