2014-10-05 186 views
2

我想在应用程序生命周期中存储某些.txt文件。我想用Environment.SpecialFolder.ApplicationData无法创建文件“c: User ... Appdata Roaming ...”。访问被拒绝

所以我创建

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

我越来越

无法创建文件 “C:\用户\应用程序数据\漫游...” 。访问被拒绝。

+0

你需要写的吗?你可以写入临时目录(认为它是'Path.GetTempDirectory()')或其他地方? – 2014-10-05 10:11:34

+0

你的代码是如何执行的?它是在你的Windows帐户下运行的命令行吗?它是一个Windows服务? IIS托管的网站作为服务帐户运行? – 2014-10-05 10:13:04

+0

@PhilipPittle它是一个简单的WPF应用程序。 – user1765862 2014-10-05 10:14:48

回答

3

考虑使用Isolated Storage,您保证读取/写入权限。

写作:

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(); 
    } 
}