0

我有一个适用于 Windows Store 的应用程序,我想做的是从文件中读取文本。我有两个文本字段。descriptionTextField 接受新行。

    // Read from file
    public async Task ReadFile()
    {
        try
        {
            // get the file
            StorageFile notesStorageFile = await localFolder.GetFileAsync("NotesData.txt");
            var readThis = await FileIO.ReadLinesAsync(notesStorageFile);
            foreach (var line in readThis)
            {
                notesRepository.Add(new Note(line.Split(';')[0], line.Split(';')[1]));
            }
            Debug.WriteLine("File read successfully.");
        }
        catch (FileNotFoundException ex)
        {
            Debug.WriteLine("Error1: " + ex);
        }
    }

现在如果NotesData.txt有:

鸡蛋;描述鸡蛋;

它的工作文件。

但是如果NotesData.txt有:

杂货;买10个鸡蛋

买1公斤肉;

我得到索引超出范围的错误。我只是不知道如何修复 ReadFile() 代码。

当我调用该方法时出现异常。我认为问题在于可以接受新行的descriptionTextBox。

NotesData.txt

苹果;说明苹果; // 工作正常

梨; 描述行 1

描述第 2 行

描述第 3 行;// 问题

梨; 描述行 1;// 工作正常

4

2 回答 2

1

这一行:

notesRepository.Add(new Note(line.Split(';')[0], line.Split(';')[1]));

假设您总是在一行中至少有一个分号。如果您的文件中有一行没有该行(例如空行),那么它将失败。

目前尚不清楚您的问题出在哪里,因为您还没有说异常来自哪里,但这是我的第一个猜测。

我也只会拆分一次:

string[] bits = line.Split(';');
if (bits.Length >= 2)
{
    // What do you want to do with lines with more than one semi-colon?
    notesRepository.Add(bits[0], bits[1]);
}
else
{
    // Handle lines without a semi-colon at all.
}
于 2012-12-29T09:14:23.273 回答
1

在我看来,您正在尝试回读您之前保存的文件的内容,而您遇到的问题只是您选择用于保存数据的格式的结果。看着它,新的线路并不是你将要遇到的唯一困难。如果用户决定在其中一个文本框中输入分号怎么办?你在阻止吗?

我建议您放弃自己的序列化格式,而使用现有的一种。如果您notesRespositoryList<Note>这可能是您的 XML (反)序列化代码:

private async Task Save(List<Note> notesRepository)
{
    var xmlSerializer = new XmlSerializer(typeof (List<Note>));
    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("notes.xml", CreationCollisionOption.ReplaceExisting))
    {
        xmlSerializer.Serialize(stream, notesRepository);
    }
}

private async Task<List<Note>> Load()
{
    var xmlSerializer = new XmlSerializer(typeof(List<Note>));
    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("notes.xml"))
    {
        return (List<Note>) xmlSerializer.Deserialize(stream);
    }
}

这对于 JSON:

private async Task Save(List<Note> notesRepository)
{
    var jsonSerializer = new DataContractJsonSerializer(typeof (List<Note>));
    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("notes.json", CreationCollisionOption.ReplaceExisting))
    {
        jsonSerializer.WriteObject(stream, notesRepository);
    }
}

private async Task<List<Note>> Load()
{
    var jsonSerializer = new DataContractJsonSerializer(typeof(List<Note>));
    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("notes.json"))
    {
        return (List<Note>)jsonSerializer.ReadObject(stream);
    }
}

当存储库变得太大而无法始终加载并作为一个整体保存时,您甚至可以考虑像SQLite这样的结构化存储。

于 2012-12-30T07:48:22.773 回答