Windows Phone 7 : FileStream exception

2019-02-19 01:33发布

问题:

I try to use FileStream (using namespace System.IO) but I get an exception :

Attempt to access the method failed 

Here is the code :

FileStream fs = new FileStream("file.txt", FileMode.Create); 

I searched on microsoft.com and I found that this error is because I use a bad library reference.

But in my project, I compile with mscorlib.dll from folder : C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0

I need some help, please.

回答1:

You will need to use IsolatedStorage, for example:

Place at the top of your file:

using System.IO.IsolatedStorage;

Then in your method do this:

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (var istream = new IsolatedStorageFileStream("File.txt", FileMode.OpenOrCreate, store))
    {
        using (var sw = new StreamWriter(istream))
        {
            sw.Write("Some Stuff");
        }
    }
}

A great example and explanation of this and other operations can be found here: http://msdn.microsoft.com/en-us/library/cc265154(v=VS.95).aspx#Y300

You can look through your IsolatedStorage by using the Windows Phone 7 IsolatedStorageExplorer

A good place to start for documentation: http://msdn.microsoft.com/library/ff626516(v=VS.92).aspx

Also here: http://create.msdn.com/en-us/education/documentation



回答2:

On WindowsPhone you must use IsolatedStorage - see this tutorial for example - http://3water.wordpress.com/2010/08/07/isolated-storage-on-wp7-ii/

Read:

    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    using (var readStream = new IsolatedStorageFileStream(fileName, FileMode.Open, store))
    using (var reader = new StreamReader(readStream))
    {
        return reader.ReadToEnd();
    }

Write:

    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    using (var writeStream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
    using (var writer = new StreamWriter(writeStream))
    {
        writer.Write(content);
    }