你好:
在本文中:您将学习写入或读取文本文件。
让我们开始:
首先创建一个新项目(ConsoleApp或WinApp)。
并且确保您的程序使用以下名称空间:
using System;
using System.IO;
using System.Diagnostics;
现在,我们将开始将文本写入文件:
1)-创建一个新的流编写器并打开文件:
TextWriter tw = new StreamWriter(@"C:\Hello.txt");
2)-将文字写入档案:
tw.WriteLine("Hello");
3)-关闭文件。
tw.Close();
4)-启动文件:
Process.Start(@"C:\Hello.txt");
这是所有代码:
//Creating a new stream-writer and opening the file.
TextWriter tsw = new StreamWriter(@"C:\Hello.txt");
//Writing text to the file.
tsw.WriteLine("Hello");
//Close the file.
tsw.Close();
//Launch the file.
Process.Start(@"C:\Hello.txt");
Console.WriteLine("You're done, press any key to exit...");
Console.ReadKey();
现在,我们将开始从文件读取文本:
1)-创建一个新的流读取器并打开文件:
TextReader trs = new StreamReader(@"C:\Hello.txt");
2)-读取文件的文本:
//Reading all the text of the file.
Console.WriteLine(trs.ReadToEnd());
//Or Can Reading a line of the text file.
//Console.WriteLine(trs.ReadLine());
3)-关闭文件:
trs.Close();
这是所有代码:
//Creating a new stream-reader and opening the file.
TextReader trs = new StreamReader(@"C:\Hello.txt");
//Reading all the text of the file.
Console.WriteLine(trs.ReadToEnd());
//Or Can Reading a line of the text file.
//Console.WriteLine(trs.ReadLine());
//Close the file.
trs.Close();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
希望这对您有所帮助。
From: https://bytes.com/topic/net/insights/673819-write-read-text-file-c