xamarin.android 文本文件读写

//写文件

public async Task SaveCountAsync(int count)

{

var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "count.txt");

//  bool b1 = File.Exists(backingFile);

using (var writer = File.CreateText(backingFile))

{

try

{

await writer.WriteLineAsync(count.ToString());//异步写入,避免大量写入时卡死

}

catch (Exception ex)

{

throw;

}

}

}

//读文件

public async Task<int> ReadCountAsync()

{

var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "count.txt");

bool b = File.Exists(backingFile);

if (backingFile == null || !File.Exists(backingFile))

{

return 0;

}

var count = 0;

using (var reader = new StreamReader(backingFile, true))

{

string line;

while ((line = await reader.ReadLineAsync()) != null)

{

if (int.TryParse(line, out var newcount))

{

count = newcount;

}

}

}

return count;

}

(0)

相关推荐