【问题标题】:How to transform array into textfile?如何将数组转换为文本文件?
【发布时间】:2011-04-21 07:08:12
【问题描述】:

我目前正在创建一个 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();
     }

FavoriteList.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.");

        }

【问题讨论】:

    标签: c# arrays windows-phone-7


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      如果您想在列表框中显示文件的内容(例如行),请立即读取整个文件内容并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);
      

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 2016-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-14
        • 2019-09-12
        相关资源
        最近更新 更多