我正在尝试将我的数组中的所有数据转换为textfile,以便逐个读取所有项目并将其保存到一个独立的存储中并将其显示在另一个页面列表框中。
我试过这个但是我遇到错误,说明“在IsolatedStorageFileStream上不允许操作”。我需要帮助,请尽快回复我。谢谢!
//save list to favourite list
private void addListBtn_Click(object sender, RoutedEventArgs e)
{
///////for-loop to access userDrinksList
//////transform array into textfile, one line for each drink
///////write in quantity of file into isolated storage using write line function
for (int i = 0; i < (Application.Current as App).userDrinksList.Count; i++)
{
//Obtain the virtual store for application
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
//Create a new folder and call it "ListFolder"
storage.CreateDirectory("ListFolder");
//Create a new file and assign a StreamWriter to the store and this new file (myFile.txt)
//Also take the text contents from the txtWrite control and write it to myFile.txt
// StreamReader readFile = null;
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.OpenOrCreate, storage));
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.Open, storage));
string myFile = readFile.ReadToEnd();
string[] lines = myFile.Split(System.Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
//write content inside myFile.txt
writeFile.WriteLine(myFile);
//retrieveDrinksListBox.Items.AddRange(lines);
//writeFile.Close();
}
答案 0 :(得分:0)
您能否提供有关抛出异常的更多信息?通过阅读您的代码,您似乎正在尝试附加到该文件。您可以在创建StreamReader
期间将FileMode
设置为Append
来消除StreamWriter
。见下文:
StreamWriter writeFile = new StreamWriter(
new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.Append, storage));
FileMode.Append
将附加到文件(如果存在),或创建新文件。
此外,我不确定您是否打算让writeFile.WriteLine(myFile)
行写myFile
而不是lines
变量(您的数据)中存储的内容。
答案 1 :(得分:0)
当您尝试从刚刚开始写入的文件中读取时,您会看到异常:
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.Open, storage
));
问题还在于你在阅读文件时从不关闭文件(虽然你在代码中没有得到足够的文件来解决它)。您拥有的所有代码都很好,您只需要重新排序即可。尝试
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.Open, storage));
string myFile = readFile.ReadToEnd();
readFile.Close();
//Create a new file and assign a StreamWriter to the store and this new file (myFile.txt)
//Also take the text contents from the txtWrite control and write it to myFile.txt
// StreamReader readFile = null;
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.OpenOrCreate, storage));
string[] lines = myFile.Split(System.Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
//write content inside myFile.txt
writeFile.WriteLine(myFile);
//retrieveDrinksListBox.Items.AddRange(lines);
writeFile.Close();