Почему текст, записанный в файл через StreamWriter, не сохраняется при перезагрузке страницы? (Xamarin) - PullRequest
0 голосов
/ 28 марта 2020

Я пытаюсь записать несколько строк в текстовый файл, чтобы сохранить эту информацию, когда пользователь переключает страницы. Однако строки, кажется, никогда не сохраняются.

Запись. (источник строк для записи в файл)

<Entry 
x:Name="Entry"
Placeholder="Username"
WidthRequest = "200"
VerticalOptions = "Start"
HorizontalOptions = "Center"
/>

Код для записи информации в файл.

        private void Write()
        {

            StreamWriter sw = new StreamWriter(path);
            sw.WriteLine(txtStorage.Length);

            //Writes length so that txtStorage can be correct length later

            sw.WriteLine(Entry.Text);

            //Writes username entered in this instance of the page

            for (int i = 0; i < txtStorage.Length; i++)
            {
                sw.WriteLine(txtStorage[i]);

                //Writes usernames stored from previous instances
            };
            sw.Close();
        } 

Код для чтения файла.

        {
            StreamReader sr = new StreamReader(path);
            txtStorage = new string[Convert.ToInt32(sr.ReadLine())];

            //updates txtstorage to new length written in text file

            for (int i = 0; i < txtStorage.Length; i++)
            {
                txtStorage[i] = sr.ReadLine();
                //puts all usernames back into txtstorage
            };

            sr.Close();
        } 

Все имена пользователей из предыдущих экземпляров не сохраняются. Что я делаю не так?

1 Ответ

0 голосов
/ 28 марта 2020

когда вы пишете файл, вы делаете это

// 1. write the length of the array
sw.WriteLine(txtStorage.Length);

// 2. write the user name
sw.WriteLine(Entry.Text);

// 3. write the array
for (int i = 0; i < txtStorage.Length; i++)

это сгенерирует файл примерно так

3
myusername
user1
user2
user3

затем, когда вы читаете файл, вы делаете это

// 1. read the length as a string
txtStorage = new string[Convert.ToInt32(sr.ReadLine())];

// 2. you aren't doing anything to handle line #2

// 3. you are using the LENGTH of txtstorage, which is 1, so your loop is only executing once
// and since you skipped #2, you are also starting on the wrong line
for (int i = 0; i < txtStorage.Length; i++)

вместо этого сделайте это

// 1. read the length as an int
var ndx = int.Parse(sr.ReadLine());

// 2. read the user name
var user = sr.ReadLine();

// 3. use ndx as the loop counter, starting on the correct line
for (int i = 0; i < ndx; i++)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...