Does IsolatedStorage File.Append mode has an error with the the '\n'?

元气小坏坏 提交于 2020-01-03 19:09:32

问题


When appending a file using IsolatedStorage API and adding a \n at the end of the string the file is empty and if adding it in the beginning of the string it erases the file then adds the requested data only

    IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
                string fileContents = "\n"+str+ " " + txtblock1.Text;
                byte[] data = Encoding.UTF8.GetBytes(fileContents);
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("Th.txt", FileMode.Append, file))
                {
                    stream.Seek(0, SeekOrigin.End);
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                }

So what should I do in that case to add a new line then write in the file ?


回答1:


I've not come across that issue but try using Environment.NewLine instead

string fileContents = Environment.NewLine + str + " " + txtblock1.Text;

or \r\n.

string fileContents = "\r\n" + str + " " + txtblock1.Text;

Generally, Environment.NewLine is fine but there may be certain scenarios where you want more control over the characters in which case you can use \r\n to add a new line.

Edit based on comment. Environment.NewLine is working fine in Append mode.

string fileContents = Environment.NewLine + "test";
byte[] data = Encoding.UTF8.GetBytes(fileContents);

using (var file = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (var stream = new IsolatedStorageFileStream("Th.txt", FileMode.Append, file))
    { 
         stream.Write(data, 0, data.Length);
    }

    using (var read = new IsolatedStorageFileStream("Th.txt", FileMode.Open, file))
    {
         var stream = new StreamReader(read, Encoding.UTF8);
         string full = stream.ReadToEnd();
         Debug.WriteLine(full);
    }

}


来源:https://stackoverflow.com/questions/17926581/does-isolatedstorage-file-append-mode-has-an-error-with-the-the-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!