Hosting in a basic configuration can be a developer’s pain when it comes to file operations. Usually the webspace doesn’t allow files to be created which has a good reason in that configuration, though.
A very smart way to deal with that is to use Isolated Storages. That way all the files are saved in a virtual storage which also means that you can control the access level which is pretending conflicts with other applications. That’s how it could look like:
176 // Filestore init
177 IsolatedStorageFile isoStore = IsolatedStoargeFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User, null, null);
178
179 // Create dir
180 isoStore.CreateDirectory(“myAppData”);
181 isoStore.CreateDirectory(“myAppData/settings”);
182
183 // Write File into Store
184 IsolatedStoargeFileStream isoStream1 = new IsolatedStorageFileStream(“myAppdData/hello.txt”, System.IO.FileMode.Create, isoStore);
185 byte[] content = Encoding.UTF8.GetBytes(“Hello!”);
186 isoStream1.Write(content, 0, content.Length);
187
188 // Read file
189 IsolatedStorageFileStream isoStream2 = new IsolatedStorageFileStream(“myAppData/hello.txt”, System.IO.FileMode.Open, isoStore);
190 byte[] content2 = new byte[isoStream2.Length];
191 isoStream2.Read(content2, 0, content2.Length);
192 isoStream2.Close();
193
194 Response.Write(Encoding.UTF8.GetString(content2));
195
196 // delete store
197 isoStore.Remove();
That’s all, a pretty clean approach for dealing with files in ASP.NET due to hosting restrictions. Nevertheless it’s also interesting to use in Desktop Applications due to the customized privileges for that storage.
2 comments ↓
Hi Andreas,
I have read your file operations blog.
I am facing one problem in which I want to write one XML file on servers directory.
Is this is possible if I change virtual directories write permission. If you are having some idea regarding this then please send me the code regarding this.
Hi Ray, are you on a virtual Server? The folder needs to be writable by ASP.NET.
Leave a Comment