C#匯出字串為txt格式
阿新 • • 發佈:2018-11-12
using System; using System.IO; using System.Text; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; // This text is added only once to the file. if (!File.Exists(path)) { // Create a file to write to. string createText = "Hello and Welcome" + Environment.NewLine; File.WriteAllText(path, createText, Encoding.UTF8); } // This text is always added, making the file longer over time // if it is not deleted. string appendText = "This is extra text" + Environment.NewLine; File.AppendAllText(path, appendText, Encoding.UTF8); // Open the file to read from. string readText = File.ReadAllText(path); Console.WriteLine(readText); Console.ReadKey(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace StreamReadWrite { class Program { static void Main(string[] args) { // Get the directories currently on the C drive. DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories(); // Write each directory name to a file. //檔案預設建立在Debug目錄下,若加上路徑則在相應路徑下建立檔案如@"c:\CDriveDirs.txt",則在C盤建立 using (StreamWriter sw = new StreamWriter("CDriveDirs.txt")) { foreach (DirectoryInfo dir in cDirs) { sw.WriteLine(dir.Name); } } // Read and show each line from the file. string line = ""; using (StreamReader sr = new StreamReader("CDriveDirs.txt")) { while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } } }