【问题标题】:" FileStream or File don't exist in the current context" trying to access File object in c#“当前上下文中不存在 FileStream 或 File”尝试在 c# 中访问 File 对象
【发布时间】:2014-06-28 12:32:43
【问题描述】:
如here 所述,我无法访问 System.IO 中的文件对象。
像这样简单的代码会引发 FileStream 或 File 在当前上下文中不存在的错误。
FileStream fs = File.Open(filePath, FileMode.Open);
我正在尝试在 Visual Studio 2013 中用 C# 编写一个 Windows 应用商店应用程序。
我已经坚持了几个小时,不知道为什么它不起作用。任何帮助将不胜感激。
【问题讨论】:
-
如果我理解正确的话,windows 存储安全模型通常会限制任意文件访问。您可以阅读其中的一些内容here、here 和 here。您是否尝试访问受限路径中的文件?
-
-
标签:
c#
windows-store-apps
microsoft-metro
【解决方案1】:
可以是Isolated Storage 问题
以下代码示例获取一个隔离存储并检查存储中是否存在名为 TestStore.txt 的文件。如果它不存在,它会创建文件并将“Hello 隔离存储”写入文件。如果 TestStore.txt 已经存在,则从文件中读取示例代码。
using System;
using System.IO;
using System.IO.IsolatedStorage;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
if (isoStore.FileExists("TestStore.txt"))
{
Console.WriteLine("The file already exists!");
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore.txt", FileMode.Open, isoStore))
{
using (StreamReader reader = new StreamReader(isoStream))
{
Console.WriteLine("Reading contents:");
Console.WriteLine(reader.ReadToEnd());
}
}
}
else
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore.txt", FileMode.CreateNew, isoStore))
{
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Hello Isolated Storage");
Console.WriteLine("You have written to the file.");
}
}
}
}
}
}
更多关于Isolated Storage