错误“IsolatedStorageFileStream不允许操作”。 wp7
问题描述:
我想从IsolatedStorage
读取一个文本文件,并检查它是否包含一个字符串。如果不是,则将该字符串添加到文件的末尾。但是当我试图将字符串写入文件时,出现错误:"Operation not permitted on IsolatedStorageFileStream."
。我的代码如下所示。我怎样才能克服这个问题?错误“IsolatedStorageFileStream不允许操作”。 wp7
public void AddToDownloadList()
{
IsolatedStorageFile downloadFile=IsolatedStorageFile.GetUserStoreForApplication();
try
{
string downloads = string.Empty;
if (!downloadFile.DirectoryExists("DownloadedFiles"))
downloadFile.CreateDirectory("DownloadedFiles");
if(downloadFile.FileExists("DownloadedFiles\\DownloadList.txt"))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile("DownloadedFiles\\DownloadList.txt",FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(downloadStream))
{
downloads = reader.ReadToEnd();
reader.Close();
}
downloadFile.DeleteFile("DownloadedFiles\\DownloadList.txt");
}
downloadFile.CreateFile("DownloadedFiles\\DownloadList.txt");
string currentFile = FileName;
if (!downloads.Contains(currentFile))
{
downloads += currentFile;
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("DownloadedFiles\\DownloadList.txt", FileMode.Create, FileAccess.Write, downloadFile)))
{
writeFile.Write(currentFile + ",");
writeFile.Close();
}
}
}
catch (Exception ex)
{
string message = ex.Message;
}
}
答
我觉得您遇到的问题已经做在其中创建由newing了IsolatedStorageFileStream的StreamWriter的行 - 当你已经应该从downloadFile.CreateFile返回正确的()调用。
试试这个代码,我认为它你想做什么:
public static void AddToDownloadList()
{
try
{
AddToDownloadList("DownloadedFiles", "this file name", "DownloadedFiles\\DownloadList.txt");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
}
}
public static void AddToDownloadList(string directory, string fileName, string filePath)
{
string downloads = string.Empty;
using (IsolatedStorageFile downloadFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!downloadFile.DirectoryExists(directory))
downloadFile.CreateDirectory(directory);
if (downloadFile.FileExists(filePath))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile(filePath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(downloadStream))
{
downloads = reader.ReadToEnd();
reader.Close();
}
}
string currentFile = fileName;
if (!downloads.Contains(currentFile))
{
downloadFile.DeleteFile(filePath);
using (IsolatedStorageFileStream stream = downloadFile.CreateFile(filePath))
{
downloads += currentFile;
using (StreamWriter writeFile = new StreamWriter(stream))
{
writeFile.Write(currentFile + ",");
writeFile.Close();
}
}
}
}
}