1. Several ways to write files in C #-Researcher-Blog Garden.html ( https://www.cnblogs.com/researcher/p/4989395.html )
Webpage content preservation:
1. FileStream.Write
string filePath = Directory.GetCurrentDirectory() + "\\" + Process.GetCurrentProcess().ProcessName + ".txt";
if (File.Exists(filePath))
File.Delete(filePath);
FileStream fs = new FileStream (filePath, FileMode.Create);
// Get byte array
string xyPointer = string.Format("X: {0}, Y: {1}", this.Location.X.ToString(), this.Location.Y.ToString());
string highWidth = string.Format("\nW: {0}, H: {1}", this.Width.ToString(), this.Height.ToString());
byte[] data = System.Text.Encoding.Default.GetBytes(xyPointer + highWidth);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
2. File.WriteAllLines
// If the file does not exist, it will be created; if it exists, it will be overwritten.
// This method writes a character array and displays the newline
string [] lines = {"first line", "second line", "third line", "fourth line"} ;
System.IO.File.WriteAllLines (@ "C: \ testDir \ test.txt", lines, Encoding.UTF8);
3. File.WriteAllText
// If the file does not exist, create it; if it exists, override
string strTest = "This example tests a string to be written to a text file.";
System.IO.File.WriteAllText (@ "C: \ testDir \ test1.txt", strTest, Encoding.UTF8);
4. StreamWriter.Write
// Before writing text to the file, process the text line
// StreamWriter one parameter defaults to overwrite
// StreamWriter the second parameter is false to overwrite the existing file, if true, append the text to the end of the file
using (System.IO.StreamWriter file = new System.IO.StreamWriter (@ "C: \ testDir \ test2.txt", true))
{
foreach (string line in lines)
{
if (! line.Contains ("second"))
{
file.Write ( line); // Directly append the end of the file without line
wrapping file.WriteLine (line); // Directly append the end of the file with line wrapping
}
}
}
2、
3、
4、
5、