我的项目中有一个名为 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/