的Windows Phone 8 - 阅读和项目在现有的TXT文件写入 [英] Windows Phone 8 - reading and writing in an existing txt file in the project
问题描述
您好我的问题是stucked,我创建了把应用程序的TXT文件。我试图从中读取数据,我之前写的内容。与该代码:
Hi i'm stucked in a problem, i created a txt file that i put on the app. I'm trying to read from it the content that i write on it before. With that code:
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);
}
给我所有的时间错误的消息,我不明白是哪里我的错。希望你会帮我的。可以肯定的内容仍然是空的。
Give me all times the message of error and i can't understand where is my mistake. Hoping that you'll help me. For sure contents is still empty.
推荐答案
我创造了我的WP 7项目中一个辅助函数最近,读包含一个文本文件在项目中。您可以尝试使用它,功能也WP 8项目的工作:
I created a helper function in my WP 7 project recently, to read a text file included in the project. You can try to use it, the function also working in WP 8 project :
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 "";
}
}
然后我可以使用函数这种方式(在此例如,文件所在文件夹的资产中):
Then I can use that function this way (in this example the file resides under Assets folder) :
var textFileContent = FileHelper.ReadFile(@"Assets\MyTextFile.txt");
这篇关于的Windows Phone 8 - 阅读和项目在现有的TXT文件写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!