嗨,我遇到了问题,我创建了一个txt文件,我把它放在应用程序上。我试图从中读取我之前写的内容。使用该代码:
public async Task WriteDataToFileAsync(string fileName, string content)
{
byte[] data = Encoding.Unicode.GetBytes(content);
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(fileName,CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
await s.WriteAsync(data, 0, data.Length);
}
}
public async Task<string> ReadFileContentsAsync(string fileName)
{
var folder = ApplicationData.Current.LocalFolder;
try
{
var file = await folder.OpenStreamForReadAsync(fileName);
using (var streamReader = new StreamReader(file))
{
return streamReader.ReadToEnd();
}
}
catch (Exception)
{
MessageBox.Show("Error");
return string.Empty;
}
}
private async void functionWhereNeedReeding()
{
string contents = await this.ReadFileContentsAsync("myimportedfile.txt");
MessageBox.Show(contents);
}
给我所有时间的错误信息,我无法理解我的错误在哪里。希望你能帮助我。确保内容仍然是空的。
答案 0 :(得分:4)
我最近在WP 7项目中创建了一个辅助函数,用于读取项目中包含的文本文件。您可以尝试使用它,该功能也适用于WP 8项目:
public static class FileHelper
{
public static string ReadFile(string filePath)
{
var ResrouceStream = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
StreamReader myStreamReader = new StreamReader(myFileStream);
return myStreamReader.ReadToEnd();
}
}
return "";
}
}
然后我可以这种方式使用该功能(在本例中,该文件位于Assets文件夹下):
var textFileContent = FileHelper.ReadFile(@"Assets\MyTextFile.txt");