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

本文关键字:文本 文件 转换 数组 | 更新日期: 2023-09-27 17:50:39

我目前正在创建一个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示例的代码示例向您展示了如何将对象写入(文件)流以及如何从同一流中再次恢复对象。

如果您想在列表框中显示文件内容(例如,行),请一次读取整个文件内容并拆分行:

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

另一种方法类似,从列表框中获取项,通过将它们与新行连接,并立即转储到file:

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