当前位置:网站首页>Reading and writing of C # file
Reading and writing of C # file
2022-07-27 06:08:00 【The moonlight is shining】
C# Reading and writing of documents
Reading documents
Use the form of file stream ,StreamRead Medium ReadLine Method , It should be noted that relative paths can also be selected
// Create a StreamReader To read the file
// using Statements can also be closed StreamReader
using (StreamReader sr = new StreamReader("c:/jamaica.txt"))
{
string line;
// Read from file and display lines , To the end of the file
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Writing documents
StreamWriter Medium WriteLine Method , It should be noted that relative paths can also be selected
using (StreamWriter sw = new StreamWriter(System.Windows.Forms.Application.StartupPath + "\\access_path.txt"))
{
//sw.Write(" Data to be saved to a file ");// Write a line without newline
sw.WriteLine(" Data to be saved to a file ");// Writes a line terminator to a text string or stream
sw.Flush();
}
Judge whether the file exists , create a file
Sometimes when reading a file, you need to judge whether the file exists :System.Windows.Forms.Application.StartupPath The path for the software to run . Note that when adding the file name, add “\”
if(File.Exists(System.Windows.Forms.Application.StartupPath+"\\access_path.txt"))
{
StreamReader sr = new StreamReader(System.Windows.Forms.Application.StartupPath + "\\access_path.txt", Encoding.Default);
string content = sr.ReadLine();// Only one line of data in the file is read here
sr.Close();
}
else
{
using (File.Create(System.Windows.Forms.Application.StartupPath + "\\access_path.txt"))
{
// Actions after file creation May be empty
}
}
Delete file
File.Delete(filePath);
边栏推荐
- 2022.6.10 stm32mp157 serial port clock learning
- C语言-程序的编译
- Linked list palindrome judgment
- Force buckle 110. Balanced binary tree
- 编程学习记录——第6课【函数】
- 力扣题解 二叉树(8)
- 编程学习记录——第8课【数组与设计五子棋,扫雷游戏】
- 人月神话阅读笔记
- Redis在windows下的idea连接不上问题
- Day 3. Suicidal ideation and behavior in institutions of higher learning: A latent class analysis
猜你喜欢
随机推荐
力扣题解 二叉树(6)
Weidongshan digital photo frame project learning (I) display ASCII characters on LCD
编程学习记录——第7课【函数】
编程学习记录——第3课【初识C语言】
【第一篇博客-展望】
arcgis for js api-入门系列
百问网驱动大全学习(一)LCD驱动
力扣第一周错题集
arcgis for js api(1) 获取featureLayer的所有字段名
C语言扫雷最新 递归展开 超详解(附源码)
力扣每日一题 剑指 Offer II 091. 粉刷房子
C# Json编码在TCP通讯中的一些使用总结
[song] rebirth of me in py introductory training (9): exception handling
物联网操作系统
socket编程一:使用fork()实现最基础的并发模式
[song] rebirth of me in py introduction training (5): List
[high concurrency] interviewer
力扣每日一题(链表模拟)
力扣题解 动态规划(7)
[first song] rebirth of me in py introductory training (2): formula programming








