" FileStream或File不存在于当前上下文中#34;试图在c#中访问File对象

时间:2014-06-28 12:32:44

标签: c# windows-store-apps microsoft-metro

我无法按照here访问System.IO中的File对象。 像这样简单的代码会抛出当前上下文中不存在FileStream或File的错误。

FileStream fs = File.Open(filePath, FileMode.Open);

我正在尝试在Visual Studio 2013中用C#编写Windows应用商店应用。 我被困在这几个小时,不知道为什么它不起作用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

可能是Isolated Storage问题

以下代码示例获取隔离存储,并检查存储中是否存在名为TestStore.txt的文件。如果它不存在,它会创建文件并写入" Hello Isolated Storage"到文件。如果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

的更多信息