我正在为Windows Phone 8编写一个应用程序。我在FileManager类中有两个方法。一个读,另一个写。
我可以毫无问题地执行步骤1-5,但是当我到达第6步时应用程序挂起 - 我收到以下错误:
访问被拒绝。 (HRESULT异常:0x80070005(E_ACCESSDENIED))
编辑 - 这是代码:
我正在使用来自http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx
的AsyncLock和AsyncSemaphore在Page1.xaml.cs中:
private void appBarButtonSave_Click(object sender, EventArgs e)
{
save().Wait();
NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
}
private Task save()
{
FileManager fileManager = new FileManager();
return fileManager.WriteToFile("TestFolder", "TestFile.html", "contents as a string");
}
在Page2.xaml.cs
中 public Preview()
{
InitializeComponent();
// Load the Preview
loadContents();
// Sample code to localize the ApplicationBar
BuildLocalizedApplicationBar();
}
private async void loadContents()
{
FileManager fileManager = new FileManager();
String strOutput = await fileManager.ReadFromFile("TestFolder", "TestFile.html");
previewBrowser.NavigateToString(strOutput);
}
FileManager.cs如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
namespace MyApp
{
class FileManager
{
StorageFolder local;
private static readonly AsyncLock m_lock = new AsyncLock();
public FileManager()
{
// Get the local folder
local = Windows.Storage.ApplicationData.Current.LocalFolder;
}
public async Task WriteToFile(String FolderName, String FileName, String contents)
{
using (await m_lock.LockAsync())
{
// Get the byte array data in String contents
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(contents.ToCharArray());
// Create a new folder name, or open it, if it already exists
var dataFolder = await local.CreateFolderAsync(FolderName.ToString(),
CreationCollisionOption.OpenIfExists);
// Create a new file, or overwrite it's contents if it already exists
var file = await dataFolder.CreateFileAsync(FileName.ToString(),
CreationCollisionOption.ReplaceExisting);
// Write the data in contents
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
}
public async Task<String> ReadFromFile(String FolderName, String FileName)
{
using (await m_lock.LockAsync())
{
if (local != null)
{
// Get the DataFolder folder
var dataFolder = await local.GetFolderAsync(FolderName.ToString());
// Get the file
var file = await dataFolder.OpenStreamForReadAsync(FileName.ToString());
// Read the data
using (StreamReader streamReader = new StreamReader(file))
{
return streamReader.ReadToEnd();
}
}
else
{
return null;
}
}
}a
}
}
答案 0 :(得分:0)
您在某处遗漏了using
(或正确关闭文件)。