Operation files are common, the project often appear such a requirement: Automatically create a file per month, and insert some data into the file, then we will analyze, whether the file exists, if there is a direct open file flow into the file to insert data, if not present, the process of creating a file and then inserting data When inserting data, the way to use the file stream is to take into account the Chinese garbled problem, the following simple implementation method
Public Static voidInsertData (stringstr) { stringFilePath =@"F:\1.txt"; if(!file.exists (FilePath)) { using(FileStream fs =NewFileStream (FilePath, FileMode.Create, FileAccess.Write)) {StreamWriter SW=NewStreamWriter (Fs,encoding.getencoding ("GB2312")); Sw. Write (str); Sw. Close (); Fs. Close (); } } //Write data in append mode, and encode format only, default is UTF-8 (Chinese garbled) using(StreamWriter TSW =NewStreamWriter (FilePath,true, Encoding.GetEncoding ("GB2312")) {tsw. Write (System.Environment.NewLine);//line BreakTSW. Write (str); Tsw. Close (); } }
C # File Flow rollup