A text to understand c# to read and write the data in the text file

Time:2021-12-4

【1】 First, we define a piece of false data. Here, we take a string as an example

static void Main(string[] args)
{
String data = "my data is going to be saved into the file. I'm so happy! Has it been overwritten? It seems to have been overwritten, but it really has been overwritten"; 
}

【2】 Then we write this data to the. TXT file
The code is as follows:

/// <summary>
        ///The process of saving data to a file;
        /// </summary>
        /// <param name="data"></param>


        public static String SavaProcess(string data) {
            System.DateTime currentTime = System.DateTime.Now;
            //Gets the day before the current date and converts it to tofiletime
            string strYMD = currentTime.AddDays(-1).ToString("yyyyMMdd");
            //Create a file name by date
            string FileName = "MyFileSend" + strYMD + ".txt";
            //Set directory
            string CurDir = System.AppDomain.CurrentDomain.BaseDirectory + @"SaveDir";
            //Determine whether the path exists
            if(!System.IO.Directory.Exists(CurDir)){
                System.IO.Directory.CreateDirectory(CurDir);
            }
            //Create if it doesn't exist
            String FilePath = CurDir + FileName;
            //Add content by file overwrite
            System.IO.StreamWriter file = new System.IO.StreamWriter(FilePath,false);
            //Save data to file
            file.Write(data);
            //Close file
            file.Close();
            //Release object
            file.Dispose();
            return FilePath;
        }

The result is to return a file path, which can or cannot be returned according to the specific situation; Let’s test whether the file is generated successfully. We call this method in the Main function. The code is as follows:

static void Main(string[] args)
        {
            String data = "my data is going to be saved into the file. I'm so happy! Has it been overwritten? It seems to have been overwritten, but it really has been overwritten";
            String filePath = SavaProcess(data);  

     Console.WriteLine(filePath);      
        }

The operation results are as follows:

Obviously, the corresponding file is generated in the relevant directory; We printed the following path in CMD:

  D:\VSProject\SavaProcessToFile\SavaProcessToFile\bin\Debug\SaveDirMyFileSend20170628.txt

The generated path is very important for our next work. It needs to be used when reading text data;

【3】 Read. TXT file data

Let’s define another method to read data:

/// <summary>
        ///Get data in file
        /// </summary>
        /// <param name="args"></param>


        public static string fileToString( String filePath ){
            string strData = "";
            try
            {
                string line;
                //Create an instance of StreamReader to read the file, and the using statement can also close StreamReader
                using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
                {                  
                    //Reads and displays lines from the file up to the end of the file
                    while ((line = sr.ReadLine()) != null)
                    {
                        //Console.WriteLine(line);
                        strData = line;
                    }                    
                }              
            }
            catch (Exception e)
            {
                //Displays an error message to the user
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            return strData;
        }

See? The parameter passed in here is the path to generate the file. Note that the type of the parameter is string representing text, not string representing string, because I use string when generating the path again, so it corresponds here;

Next, let’s test whether we have successfully read the file and whether the string we originally wrote will appear in CMD? We call the method in the Main function. The code is as follows:

static void Main(string[] args)
        {
            String data = "my data is going to be saved into the file. I'm so happy! Has it been overwritten? It seems to have been overwritten, but it really has been overwritten";
            String filePath = SavaProcess(data);
            string strData = fileToString(filePath);
            Console.WriteLine(strData);         
        }

The operation results are as follows:

As a result, the string stored at the beginning appears;

【4】 Write and read process complete code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SavaProcessToFile
{
class Program
{
/// <summary>
///The process of saving data to a file;
/// </summary>
/// <param name="data"></param>
public static String SavaProcess(string data) {
System.DateTime currentTime = System.DateTime.Now;
//Gets the day before the current date and converts it to tofiletime
string strYMD = currentTime.AddDays(-1).ToString("yyyyMMdd");
//Create a file name by date
string FileName = "MyFileSend" + strYMD + ".txt";
//Set directory
string CurDir = System.AppDomain.CurrentDomain.BaseDirectory + @"SaveDir";
//Determine whether the path exists
if(!System.IO.Directory.Exists(CurDir)){
System.IO.Directory.CreateDirectory(CurDir);
}
//Create if it doesn't exist
String FilePath = CurDir + FileName;
//Add content by file overwrite
System.IO.StreamWriter file = new System.IO.StreamWriter(FilePath,false);
//Save data to file
file.Write(data);
//Close file
file.Close();
//Release object
file.Dispose();

return FilePath;
}

/// <summary>
///Get data in file
/// </summary>
/// <param name="args"></param>
public static string fileToString(String filePath){
string strData = "";
try
{
string line;
//Create an instance of StreamReader to read the file, and the using statement can also close StreamReader
using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
{ 
//Reads and displays lines from the file up to the end of the file 
while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
strData = line;
} 
} 
}
catch (Exception e)
{
//Displays an error message to the user
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
return strData;
}

static void Main(string[] args)
{
String data = "my data is going to be saved into the file. I'm so happy! Has it been overwritten? It seems to have been overwritten, but it really has been overwritten";
String filePath = SavaProcess(data);
string strData = fileToString(filePath);
Console.WriteLine(strData); 
}
}
}

The above is the details of c# reading and writing text file data. For more information about c# reading and writing text file data, please pay attention to other related articles of developeppaer!