Windows Phone 8 - reading and writing in an existing txt file in the project

我的未来我决定 提交于 2019-12-01 10:26:06

问题


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.


回答1:


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");


来源:https://stackoverflow.com/questions/21135339/windows-phone-8-reading-and-writing-in-an-existing-txt-file-in-the-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!