Как преобразовать массив в текстовый файл? - PullRequest
0 голосов
/ 21 апреля 2011

В настоящее время я создаю приложение для 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.");

        }

Ответы [ 2 ]

0 голосов
/ 21 апреля 2011

Если вы хотите отобразить содержимое вашего файла (скажем, строки) в списке, прочитайте все содержимое файла сразу и split строки:

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

В другом случае аналогично, извлекайте элементы из списка, соединяя их с новой строкой, и сразу сбрасывайте в файл:

string fileContents = string.Join(Environment.NewLine, 
                                  retrieveDrinksListBox.Items.Cast<string>());
writeFile.WriteLine(fileContents);
0 голосов
/ 21 апреля 2011

Вы должны записать сериализованные элементы / данные списка, а не сам список.

При повторном чтении их необходимо десериализовать. Пример BinaryFormatter на MSDN содержит примеры кода, показывающие, как записать объект в поток (файл) и как восстановить объект из этого тот же поток.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...