网站的宗旨,手机网站的开发,厦门建设局官网首页,影视推广赚钱咨询区 ApprenticeHacker#xff1a;在 C# 中有很多种读写文件的方式 (文本文件#xff0c;非二进制)。为了践行 do more, write less 的思想#xff0c;现寻找一种最简单最少代码量的方式#xff0c;因为在我的项目中有太多的功能需要读写文件了。回答区 vc 74#xff1a… 咨询区 ApprenticeHacker在 C# 中有很多种读写文件的方式 (文本文件非二进制)。为了践行 do more, write less 的思想现寻找一种最简单最少代码量的方式因为在我的项目中有太多的功能需要读写文件了。回答区 vc 74可以使用 C# 中的 File.ReadAllText 和 File.WriteAllText。MSDN 上提供了如下的例子。
// Create a file to write to.
string createText Hello and Welcome Environment.NewLine;
File.WriteAllText(path, createText);...// Open the file to read from.
string readText File.ReadAllText(path);Roland可以通过 扩展方法 的方式实现最少代码的写法我敢打赌绝对是最简单的做法就是在 string 上做扩展具体用什么名字就取决于个人喜好了。
using System.IO;//File, Directory, Pathnamespace Lib
{/// summary/// Handy string methods/// /summarypublic static class Strings{/// summary/// Extension method to write the string Str to a file/// /summary/// param nameStr/param/// param nameFilename/parampublic static void WriteToFile(this string Str, string Filename){File.WriteAllText(Filename, Str);return;}// of course you could add other useful string methods...}//end class
}//end ns有了扩展方法后用起来就非常简单了。
using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{class Program{static void Main(string[] args){Hello World!.WriteToFile(c:\temp\helloworld.txt);return;}}//end class
}//end ns看起来是不是非常美好所以我决定分享给你们啦祝使用愉快。点评区 小编在学习C#的早期都是通过 StreamWriter 和 StreamReader 来操控文件参考代码如下static void Main(string[] args){using (StreamWriter writetext new StreamWriter(write.txt)){writetext.WriteLine(writing in text file);}using (StreamReader readtext new StreamReader(readme.txt)){string readText readtext.ReadLine();}}后来莫名其妙的知道了 File 下居然还有 Read 和 Write 系列静态扩展方法后再也回不去了。。。????????????不过奇怪也没啥奇怪的底层大多还是 StreamWriter 和 StreamReader 的封装而已如下图所示原文链接https://stackoverflow.com/questions/7569904/easiest-way-to-read-from-and-write-to-files