Isolated Storage
For storing per-user settings (as opposed to documents that the user might want to manipulate directly in the file system), you should consider using the .NET Framework's isolated storage system. This is really just another way to access files stored under the user profile directory, but the .NET Framework manages the location of the storage so that each assembly gets its very own private root directory where files can be stored. Once you realize that an isolated storage file is just a real file in the file system, you'll see how easy it is to use. Because IsolatedStorageFileStream derives from FileStream, if you've used the FileStream class, using a file from Isolated Storage isn't any different. Here's an example that creates a text file using IsolatedStorage.
using System; using System.IO; using System.IO.IsolatedStorage; class App { static void Main() { IsolatedStorageFile myRoot = IsolatedStorageFile.GetUserStoreForAssembly(); using (FileStream media = new IsolatedStorageFileStream("myFile.txt", FileMode.Create, FileAccess.Write, FileShare.None, myRoot)) using (StreamWriter w = new StreamWriter(media)) { w.Write("Hello, isolated storage!"); } } }
There is now a file called myFile.txt somewhere on your hard drive. To find it, configure Explorer to show hidden files and drill down into your user profile directory a bit: c:\Documents and Settings\[user name]\Local Settings\Application Data\IsolatedStorage. From here names are mangled, but just keep drilling down and you'll eventually find your file. Open it in Notepad and see that there's nothing magical happening here. To see how your assembly's storage location is identified, use storeadm /list. You'll notice that by default your storage is indexed by your assembly's URL. This means that, if your assembly is loaded from a different location, it will be looking at a new storage location. If this is a problem, give your assembly a strong name. Now the storage location will depend only on your assembly's strong name, which means that, if the version of your assembly changes, it will be looking at a new storage location, but this is usually acceptable if you plan ahead. Run storeadm /list after giving the previous example a strong name and see how things change.