I use this code to write a string to a file.
var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write);
var sw = new StreamWriter(fs, Encoding.UTF8);
sw.Write(dataString);
fs.Flush();
sw.Flush();
sw.Close();
When I debug it, I see the dataString correct. However, after writing to a file, there are some strings have wrong orders. Should I add a thread Sleep after writing data to the file because right after writing data to the file, I read it back for other process.
OR probably there is better way to write a string to a file?
Thanks in advance.
Yes, there’s a simpler way. Use
File.WriteAllTextorFile.AppendAllText.Apart from being more concise, another advantage is that the file will be correctly closed even if there is an exception. However, I doubt that it will change the order in which the data is written to the file.