C# write and read TXT files
Write
/// <summary> /// Write strings to txt file/// </summary> /// <param name="value">Content</param>/// <param name="isClearOldText">Whether to clear old text</param>private void Wriete(string value, bool isClearOldText = true) { string path = "Path to txt file"; //Whether to clear the old text if (isClearOldText) { //Clear the txt file using (FileStream stream = (path, , )) { (0, ); (0); } } //Write content using (StreamWriter writer = new StreamWriter(path, true)) { (value); } }
Read
/// <summary> /// Read the txt file and return the contents in the file/// </summary> /// <returns>txt file content</returns>private string ReadTxTContent() { try { string s_con = ; // Create an instance of StreamReader to read the file // Using statement can also close StreamReader using (StreamReader sr = new StreamReader("Path to txt file")) { string line; // Read and display lines from the file until the end of the file while ((line = ()) != null) { s_con += line; } } return s_con; } catch (Exception e) { (); return null; } }
Read and write xml in C#
About xml
- XML refers to an Extensible Markup Language
- XML is a markup language, very similar to HTML
- XML is designed to transmit data, not display data
- The XML tag is not predefined, you need to define the tag yourself
- XML is designed to be self-descriptive
- XML is the recommended standard for W3C
//Format statement<!--?xml version="1.0" --> useencodingCoding of attribute declaration document <!--?xml version="1.0" encoding="UTF-8" --> usestandaloneAttribute description whether the document is independent <!--?xml version="1.0" encoding="UTF-8" standalone="yes" -->
Customize xml file
<?xml version="1.0" encoding="utf-8"?> <xcsharp > <app > <name>Advanced Mathematics</name> <age>12</age> </app> </xcsharp >
Read XML code
static void Main(string[] args) { //Load the XML file in XDocument document = ("E:\\"); //Get the root element of the XML to operate XElement root= ; XElement ele= ("app"); //Get the value of the name tag XElement shuxing= ("app"); (); //Get all child elements under the root element IEnumerableenumerable = (); foreach (XElement item in enumerable) { foreach (XElement item1 in ()) { (); } (("id").Value); } (); }
Write XML code
static void Main(string[] args) { //Get the root node object XDocument document = new XDocument(); XElement root = new XElement("xcsharp"); XElement book = new XElement("app"); ("name", "test"); ("age", "12"); (app); ("e:\\"); (); }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.