无法创建文件"c:User...AppdataRoaming..." 。访问被拒绝



我想在应用程序生存期内存储某些.txt文件。我想用Environment.SpecialFolder.ApplicationData

所以我创建了

 string myFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), address.GetHashCode() + ".txt");
...
 File.WriteAllText(myFilename, someTextContent);

我得到

无法创建文件"c:\User…\Appdata\Roaming…"。访问被拒绝

考虑使用独立存储,您可以保证使用它进行读/写访问。

写作:

IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore.txt", FileMode.CreateNew, isoStore))
{
    using (StreamWriter writer = new StreamWriter(isoStream))
    {
        writer.WriteLine("Hello Isolated Storage");
    }
}

读数:

using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore.txt", FileMode.Open, isoStore))
{
    using (StreamReader reader = new StreamReader(isoStream))
    {
        string contents = reader.ReadToEnd();
    }
}

最新更新