使用List写入文本文件

时间:2014-10-08 19:13:14

标签: c#-4.0 file-io

我有100个属性的列表。所以如果我有数千条记录,我的应用程序将在写入文本文件时挂起。

那么是否可以轻松快捷地写入文本文件。

感谢任何帮助。

提前致谢

1 个答案:

答案 0 :(得分:0)

您应该异步加载所有这些工作,这样您就不会过度使用/重载主线程并保持您的app / UI响应。你可以这样管理它:

protected void buttonSaveClick(sender object, EventArgs e) //Assuming you call your save from a button
{
    string filePath = FilePath(Constants.Data, filename));
    StringBuilder sb = new StringBuilder();

    foreach(var sublist in _mylist) 
    {
        //This will loop only through object's public properties
        foreach(var prop in sublist.GetType().GetProperties())
            if(prop.CanRead)
                sb.AppendLine(prop.GetValue(sublist, null));
    }

    buttonSaveClick.Enabled = false; //Disable the UI so the user can't cause an error clicking again

    try
    {
        await WriteTextAsync(filePath, _textFileHeader.DataColumnHeader(columnnames));
        await WriteTextAsync(filePath, sb.ToString());
    }
    catch(Exception ex)
    {
        buttonSave.Enabled = true; //Enable UI again on error
        //Log and/or show error to user
    }

    buttonSave.Enabled = true; //Enable UI again on success
}

private async Task WriteTextAsync(string filePath, string text)
{
    byte[] encodedText = Encoding.Unicode.GetBytes(text);

    using (FileStream sourceStream = new FileStream(filePath,
        FileMode.Append, FileAccess.Write, FileShare.None,
        bufferSize: 4096, useAsync: true))
    {
        await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
    };
}