当前位置:网站首页>C # read and write txt files
C # read and write txt files
2022-07-19 08:14:00 【Abacus】
// Write configuration information into the text
public void WriteConfigToTxt(int times, int days, string delPath)
{
try
{
string user = Environment.GetFolderPath(Environment.SpecialFolder.Templates);
string configPath = user + "\\ConfigFile";
//string logPath = "c:\\LogFile";
// Judge whether the folder under this path exists , Create a new folder if it does not exist
if (!Directory.Exists(configPath))
{
Directory.CreateDirectory(configPath);
}
// Specifies the directory for the log files
string fname = configPath + "\\ConfigFile.txt";
// Clear the text first
System.IO.File.WriteAllText(fname, string.Empty);
// Define file information objects
FileInfo finfo = new FileInfo(fname);
if (!finfo.Exists)
{
FileStream fs;
fs = File.Create(fname);
fs.Close();
finfo = new FileInfo(fname);
}
// Create a write only file stream
using (FileStream fs = finfo.OpenWrite())
{
// Create a write data stream based on the file stream created above
StreamWriter w = new StreamWriter(fs);
// Set the start position of the write data stream to the end of the file stream
w.BaseStream.Seek(0, SeekOrigin.End);
// Write content
w.Write(times.ToString() + "\n" + days + "\n" + delPath + "\n\r");
// Empty buffer contents , And write the contents of the buffer to the underlying stream
w.Flush();
// Close the write data stream
w.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
// Read txt file , And return the contents of the file
public string ReadTxTContent()
{
try
{
string user = Environment.GetFolderPath(Environment.SpecialFolder.Templates);
string contentPath = user + "\\ConfigFile";
if (Directory.Exists(contentPath))
{
string strCon = string.Empty;
// Create a StreamReader To read the file
// using Statements can also be closed StreamReader
contentPath = contentPath + "\\ConfigFile.txt";
using (StreamReader sr = new StreamReader(contentPath))
{
string line;
// Read from file and display lines , To the end of the file
while ((line = sr.ReadLine()) != null)
{
strCon += line + " ";
}
}
return strCon;
}
return null;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
边栏推荐
猜你喜欢
随机推荐
The website vulnerability repair service provider analyzes the ultra vires caused by controllable parameters
Local storage sessionstorage
Jira --- workflow call external api
本地存储 sessionStorage
真实案例:系统上线后Cpu使用率飙升如何排查?
Detailed explanation of type, user-defined type, preliminary understanding of structure
行为型模式之策略模式
Deep learning 7 deep feedforward network
Strategic model of behavioral model
mySQL 2502 2503错误
写代码遇到Qt相关问题
1669. Merge two linked lists (merge of two linked lists)
CCF-CSP《202206-2—寻宝!大冒险!》
面试题:外边距折叠问题 (块级元素在普通文档流中的BUG)
How to write the highlights of SCI papers (seriously teach you how to write)
神经网络和自动控制的联系
Convolutional neural network CNN
类型详解·自定义类型·结构体初识
深度学习之 7 深度前馈网络
[day01] preface, introductory program, constant variables