问题
I am writing some test application to write some text into a text file using StreamWriter. While executing the WriteLine method system shutdown abruptly. After rebooting the machine have observed that there are many NUL characters at the end of file.
Have searched many sites including MSDN I didn't found the solution for this problem.
Could any one help me to resolve this problem.
This can be easily reproducible if we do the following steps:
- Create WindowsApplication and place a button control on it.
In the button click event handler write the following code:
private void button1_Click(object sender, EventArgs e)
{ string str = "Welcome to the C Sharp programming world with a test application using IO operations."; StreamWriter sw = new StreamWriter(fileName, true, Encoding.Unicode, str.Length); sw.WriteLine(str); sw.Close(); }
Run the application and click on the button continuously (Do not until machine shutdown) and press the Poweroff button of the PC.
Reboot the PC and check the file it contains the following text:
Welcome to the C Sharp programming world with a test application using IO operations.
Welcome to the C Sharp programming world with a test application using IO operations.
Welcome to the C Sharp programming world with a test application using IO operations.
Welcome to the C Sharp programming world with a test application using IO operations.
Welcome to the C Sharp programming world with a test application using IO operations.
Welcome to the C Sharp programming world with a test application using IO operations.
NULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNUL
The NUL characters will appear in NotePad++ and we cannot see these characters in Normal NotePad.
Thanks in Advance
回答1:
That happens. When you append a file first its size is corrected in the directory (and that's transactional in NTFS) and then the actual new data is written. There's good chance that if you shut down the system you end up with a file appended with lots of null bytes because data writes are not transactional unlike metadata (file size) writes.
There's no absolute solution to this problem.
回答2:
I know it looks gross but this is what I had to do to solve the problem. Just put the following code after you have written the string to your file.
var lines = System.IO.File.ReadAllLines(workingFile.FullName);
//Strip the "null line" from file
if (lines[lines.Length - 1].StartsWith("\0\0\0\0\0"))
{
System.IO.File.WriteAllLines(workingFile.FullName, lines.Take(lines.Length - 1).ToArray());
}
What this does is reads all the lines in the file into an Array, if the last line is that pesky NUL line the code will write all elements of the Array minus the last element(NUL line)
来源:https://stackoverflow.com/questions/10913632/streamwriter-writing-nul-characters-at-the-end-of-the-file-when-system-shutdown