当前位置:网站首页>[C # notes] reading and writing of the contents of text files

[C # notes] reading and writing of the contents of text files

2022-07-07 02:20:00 Start()

Mainly used two API:

System.IO.StreamReader.ReadToEnd() // Stream reader Read the whole content of the text

System.IO.StreamWriter.Write(string value) // Stream writer Write text content to file


       // Read 
    public string ReadTxt(string txtPath)
    {
    
        StreamReader streamReader = new StreamReader(txtPath, Encoding.Default);
        string con = streamReader.ReadToEnd();
        streamReader.Close();
        return con;
    }





    // write in 
    /// <param name="txtPath"> File path </param>
    /// <param name="writeCon"> Write content </param>
    /// <param name="isCoverCon"> Whether to cover the content </param>
    public void WriteTxt(string txtPath, string writeCon, bool isCoverCon = false)
    {
    
        #region  If there is no text file , Just create one 
        if (!File.Exists(txtPath))
            File.Create(txtPath).Close();
        #endregion

        if (!isCoverCon)
            writeCon += ReadTxt(filePath);

        StreamWriter streamWriter = new StreamWriter(txtPath);
        streamWriter.Write(writeCon);// The content will completely cover the original text content 

        streamWriter.Close();
    }

A newly discovered simple method , Let's record :


Use C# Encapsulated two API:

System.IO.File.ReadAllText(string path, Encoding encoding); // Read

System.IO.File.WriteAllText(string path, string contents, Encoding encoding); // write in

原网站

版权声明
本文为[Start()]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130859203985.html