c# - 从 Windows Phone 7 读取文件

标签 c# windows-phone-7 c#-4.0 stream isolatedstorage

我的项目中有一个名为 data/ 的文件夹,其中包含 txt 文件

我将 Build Action 配置为所有文件的 resources

我尝试了这些不同的方式:

方法一

var resource = Application.GetResourceStream(new Uri(fName, UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
Debug.WriteLine(streamReader.ReadToEnd());

方法二

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileNames = myIsolatedStorage.GetFileNames("*.txt");

方法三

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
   using (StreamReader fileReader = new StreamReader(new IsolatedStorageFileStream(fName, FileMode.Open, isf)))
   {
      while (!fileReader.EndOfStream)
      {
        string line = fileReader.ReadLine();
        al.Add(line);
        Debug.WriteLine(line);
      }
   }
}

现在,我尝试了不同的方式来读取文件都没有成功,为什么?
问题出在哪里?

这些方法有什么问题?

fName 是文件名。
是否需要完整路径 data/filename.txt?无所谓……

请帮我解决这个愚蠢的问题,
谢谢。

最佳答案

您的第二和第三种方法是错误的。当您在应用程序本地包含文本文件时,您无法通过 IS 引用它。相反,使用此函数,如果找到,它将返回文件内容,否则它将返回 "null"。它对我有用,希望对你有用。

请注意,如果文件被设置为内容,则 filePath = "data/filename.txt" 但如果它被设置为资源,则应像这样引用 filePath = "/项目名称;组件/数据/文件名.txt”。这可能就是您的第一种方法可能失败的原因。

    private string ReadFile(string filePath)
    {
        //this verse is loaded for the first time so fill it from the text file
        var ResrouceStream = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
        if (ResrouceStream != null)
        {
            Stream myFileStream = ResrouceStream.Stream;
            if (myFileStream.CanRead)
            {
                StreamReader myStreamReader = new StreamReader(myFileStream);

                //read the content here
                return myStreamReader.ReadToEnd();
            }
        }
        return "NULL";
    }

关于c# - 从 Windows Phone 7 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12122170/

相关文章:

c# - 如何在写入文件之前清除文件

windows-phone-7 - 如何在 WP7 中隐藏软键盘?

c# - 获取媒体文件持续时间的最快方法是什么?

.net - C# 浏览器组件添加 header 参数

c# - 如何为多个元素制作if语句? C#

c# - Azure AD 异常 - AADSTS50105 - "The signed in user is not assigned to a role for the application"

silverlight-4.0 - 如何在 Windows Phone 7 Silverlight 应用程序中将图像旋转到特定角度?

c# - 基于字符串列表返回对象的模式?

c# - 使用绘制事件移动对象

c# - Entity Framework 使用扩展方法抛出异常