user2210060
user2210060

Reputation: 31

File is blank after using StreamWriter

I am trying to write some data to an existing file that is within my project(local file to the project). I used the following code

        Uri path = new Uri(@"Notes.txt", UriKind.Relative);

        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {

            using (StreamWriter writefile = new StreamWriter(new IsolatedStorageFileStream(path.ToString(), FileMode.Append, FileAccess.Write,myIsolatedStorage)))
            {
                writefile.WriteLine("hi");
                writefile.Flush();
                writefile.Dispose();
            }
        }

There is no exception/error while executing the program.However the file is blank and does not contain any data.

I have set the build action of the file as 'resource' and content as 'copy if newer'. Just to check, i removed the file and tested, it still does not give any exception, though I am trying to open in Append Mode.

Edit: I was opening the file in my development environment to check. However I later used the ISETool.exe to check for the file. But the file is not created at all !! Here is the updated code I used:

 Uri path = new Uri(@"Notes.txt", UriKind.Relative);
 using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
 using (var stream = new IsolatedStorageFileStream(path.ToString(), FileMode.OpenOrCreate, FileAccess.Write, myIsolatedStorage))
 using (var writefile = new StreamWriter(stream))
        {
            writefile.WriteLine("hi");
        }

Upvotes: 2

Views: 489

Answers (1)

Richard Szalay
Richard Szalay

Reputation: 84734

Edit

Based on your comments above, I think your problem is actually that you have misunderstood how Isolated Storage works; it stores files on your phone or inside the emulator image, neither of which are your development machine's native file system.

If you need to access the file from your development machine, you'll need a utility like Windows Phone Power Tools (c/o Alastair Pitts, above) or the SDK's isetool.exe if you don't mind the command line interface.

Original post

Two things to jump out at me:

  1. You're not disposing your IsolatedStorageFileStream
  2. You should obtain your instance of IsolatedStorageFileStream from the IsolatedStorageFile
  3. You don't need to call Dispose on writefile (that's what using does)

Try this:

using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = isolatedStorage.OpenFile(path.ToString(), FileMode.Append, FileAccess.Write))
using (var writefile = new StreamWriter(stream))
{
    writefile.WriteLine("hi");
}

Upvotes: 6

Related Questions