LTKD
LTKD

Reputation: 214

WIndows Phone 7 reading file to String

I'm trying to read a file entirely to a String variable.

I did this:

   String text;
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            using (var readStream = new IsolatedStorageFileStream("k.dat",     FileMode.Open,        store))
            using (var reader = new StreamReader(readStream))
            {
                text= reader.ReadToEnd();
            }

        textBlock1.Text = text;`

It gave me a "Operation not permitted on IsolatedStorageFileStream" message from an IsolatedStorageException.

What am I doing wrong? I tried by adding a .txt and .xml file in the file name, but it didn't work. Where am I to put the file anyway? I tried

~\Visual Studio 2010\Projects\Parsing\Parsing\k.dat

I'm parsing it later using:

XmlReader reader = XmlReader.Create(new StringReader(xmldata));
            flagLink = false;
            while (reader.Read())
            {
//and so on

Upvotes: 0

Views: 1835

Answers (2)

LTKD
LTKD

Reputation: 214

This is the entire method and this worked fully:

String sFile = "k.dat";
        IsolatedStorageFile myFile = IsolatedStorageFile.GetUserStoreForApplication();
        //myFile.DeleteFile(sFile);
        if (!myFile.FileExists(sFile))
        {
            IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile);
            dataFile.Close();
        }

        var resource = Application.GetResourceStream(new Uri(@"k.dat", UriKind.Relative));

        StreamReader streamReader = new StreamReader(resource.Stream);
        string rawData = streamReader.ReadToEnd();

        return rawData;

Upvotes: 0

ridoy
ridoy

Reputation: 6332

Try with..

string text;
string filename="k.txt";

    using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (isolatedStorage.FileExists(fileName))
        {
            StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, isolatedStorage));

            text = reader.ReadToEnd();

            reader.Close();
        }

        if(!String.IsNullOrEmpty(text))
        {
             MessageBox.Show(text);
        }
    }

EDIT:
In case of xml,

try
{
    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("test.xml", FileMode.Open); //you can use your filename just like above code
        using (StreamReader reader = new StreamReader(isoFileStream))
        {
            this.textbox1.Text = reader.ReadToEnd();
        }
    }
}
catch
{ }

Upvotes: 2

Related Questions