如何将数组转换为文本文件?

问题描述:

我目前正在创建一个Windows Phone 7应用程序。如何将数组的所有值转换为文本文件,以便可以将存储在特定数组中的所有值存储在另一个页面列表框中,然后存储在独立存储器中。 谢谢! :(如何将数组转换为文本文件?

这个方法我试过,但它不工作。 对于ViewList.xaml.cs

private void addListBtn_Click(object sender, RoutedEventArgs e) 
    { 
     //Obtain the virtual store for application 
     IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication(); 

     //Create a new folder and call it "ImageFolder" 
     myStore.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 

     StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.OpenOrCreate, myStore)); 
     writeFile.WriteLine(retrieveDrinksListBox); 
     writeFile.Close(); 
    } 

FavouriteList.xaml.cs

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) 
    { 


     //Obtain a virtual store for application 
     IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication(); 

     //This code will open and read the contents of retrieveDrinksListBox 
     //Add exception in case the user attempts to click “Read button first. 

     StreamReader readFile = null; 

     try 
     { 
      readFile = new StreamReader(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.Open, myStore)); 
      string fileText = readFile.ReadLine(); 

      if (fileText != "") 
      { 

       listNumberListBox.Items.Add("List 1"); 
      } 

      //The control txtRead will display the text entered in the file 
      listNumberListBox.Items.Add(fileText); 
      readFile.Close(); 

     } 

     catch 
     { 

      MessageBox.Show("Need to create directory and the file first."); 

     } 

您必须编写取走列表框中的序列化项目/数据,而不是列表框本身。

当阅读再次将它们反序列化。MSDN上的BinaryFormatter示例包含代码示例,向您展示如何将对象写入(文件)流以及如何从同一个流再次恢复对象。

如果你想显示在列表框中的文件的内容(比如,线),读取整个文件的内容在一次split行:

string fileText = readFile.ReadToEnd(); 
string[] lines = fileText.Split(Enviroment.NewLine.ToCharArray(), 
           StringSplitOptions.RemoveEmptyEntries); 
listNumberListBox.Items.AddRange(lines); 

其他方式是类似的,取从您的列表框项目,由joining他们用新的一行,并立即转储到文件:

string fileContents = string.Join(Environment.NewLine, 
            retrieveDrinksListBox.Items.Cast<string>()); 
writeFile.WriteLine(fileContents);