IsolatedStorage File.Append模式是否与'\ n'有错误?

时间:2013-07-29 14:24:56

标签: windows-phone-8 isolatedstorage

使用IsolatedStorage API附加文件并在字符串末尾添加\ n时,文件为空,如果在字符串的开头添加它,则会删除文件,然后仅添加请求的数据

    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();
                }

那么在这种情况下我应该怎么做才能添加新行然后写入文件?

1 个答案:

答案 0 :(得分:2)

我没有遇到过这个问题,但尝试使用Environment.NewLine代替

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

\r\n

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

通常情况下,Environment.NewLine很好,但在某些情况下您可能需要对字符进行更多控制,在这种情况下,您可以使用\r\n添加新行。

根据评论进行修改。 Environment.NewLineAppend模式下正常运行。

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);
    }

}