Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 964
Amr Abulnaga Avatar asked Jan 27 '26 11:01

Amr Abulnaga


1 Answers

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

}
like image 165
keyboardP Avatar answered Jan 31 '26 03:01

keyboardP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!